It seems that many classes (e.g. HashSet
) assume that the hashCode
of an object will not change. The documentation is clear about what the relationship between equals
and hashCode
should be.
But is it poor design to implement a hashCode
that changes across an object's life-time?
There at least needs to be point in the application where the hashCode is frozen while it is in a collection that cares. Typically, the hashCode will change while you build up the object (e.g., adding to an ArrayList), then you add it to a collection and stop changing. Later, if you remove it from the collection, you could mutate it again. I would say it is generally a best practice to use immutable data structures (ala String or your own type with finals all the way down) with collections that rely on the hashCode (e.g., HashMap key or HashSet).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With