简体   繁体   中英

Making HashSet<MyType> differ between objects with the same values

I have overridden Equal(Object comparee) method but when i add objects to my HashSet i still get doubles. What did i miss? The MyType type contains two int fields (let's say that). Is HashSet a wrong collection type, perhaps?

I wish to add some MyType thingies but so that the collection only stores the unique ones, where unique is defined by me (using Equals method or any other way).

You should always override GetHashCode() when you override Equals() . I typically return some sort of primary key, if available, for that method. Otherwise, you can check out this thread for ideas for implementing it.

The key to understanding the relationship between those two methods is:

  • If two entries have different hash codes, they are definitely not equal.
  • If two entries have the same hash code, they might be equal, so call Equals() to find out for sure.

You need to override GetHashCode() as well; otherwise, your objects will have different hashcodes and will therefore automatically be assumed to be different. Take some unique-ish value from your object and use that if available, or just generate your own.

And don't be lazy and use the same hash code for all of them, either; that will defeat the purpose of a HashSet .

So for your example with two int fields, you might do something like:

public override int GetHashCode() {
    return field1 ^ field2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM