HashSets don't keep the elements unique if you mutate their identity

匆匆过客 提交于 2019-12-04 05:46:43

You're really talking about object identity. If you're going to hash items they need to have some kind of identity so they can be compared.

  • If that changes, it is not a valid identity method. You currently have public int myint. It really should be readonly, and only set in the constructor.
  • If two objects are conceptually different (i.e. you want to treat them as different in your specific design) then their hash code should be different.
  • If you have two objects with the same content (i.e. two value objects that have the same field values) then they should have the same hash codes and should be equal.
  • If your data model says that you can have two objects with the same content but they can't be equal, you should use a surrogate id, not hash the contents.
  • Perhaps your objects should be immutable value types so the object can't change
  • If they are mutable types, you should assign a surrogate ID (i.e. one that is introduced externally, like an increasing counter id or using the object's hashcode) that never changes for the given object

This is a problem with your Tester objects, not the set. You need to think hard about how you define identity. It's not an easy problem.

When I need a 1-dimensional collection of guaranteed unique items I usually go with Dictionary<TKey, Tvalue>: you cannot add elements with the same Key, plus I usually need to attach some properties to the items and the Value comes in handy (my go-to value type is Tuple<> for many values...).

OF course, it's not the most performant nor the least memory-hungry solution, but I don't usually have performance/memory concerns.

You should implement your own IEqualityComparer and pass it to the constructor of the HashSet to ensure you get the desired equality comparer.

And as Joe said, if you want the collection to remain unique even beyond .Add(T item) you need to use ValueObjects that are created by the constructor and have no publicly visible set attributes. i.e.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!