Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, should the hashCode of an object ever change? [duplicate]

Tags:

java

hashcode

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?

like image 602
sdgfsdh Avatar asked Sep 25 '15 15:09

sdgfsdh


1 Answers

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).

like image 115
Brett Kail Avatar answered Nov 15 '22 13:11

Brett Kail