In Java, should an object's hash code ever change?

It seems that many classes (for example, HashSet) assume that the object of the hashCodeobject will not change. The documentation makes clear what the relationship between equalsand should be hashCode.

But is a design that implements hashCodethat changes throughout the life of the object uncomfortable ?

+4
source share
5 answers

At least there should be indicated an application in which the hash code is frozen while it is in the collection of interest. As a rule, hashCode will change when creating an object (for example, adding it to ArrayList), then you add it to the collection and stop changing. Later, if you remove it from the collection, you can change it again. I would say that it is best to use immutable data structures (ala String or your own type with ending ending) with collections that rely on a hash code (for example, a HashMap or HashSet key).

+5
source

No, it’s normal that hashCode changes when the mutable object changes its internal state.

, , hashCode, , , hashCode.

+2

, "". , :

, Java, hashCode

, , - .

, , JVM, Java-, - .

, .

+1

. Hash(Map|Set) - . hashCode . hashCode ( , hashCode).

0

hashCode . javadocs -

, Java, hashCode , , , . .

, , - - . . - . hashCode , .

In addition, some consider it hashCodea unique object descriptor. This is a wrong and anti-pattern. For example, the strings "Aa" and "BB" produce the same hashCode: 2112.

0
source

Source: https://habr.com/ru/post/1609011/


All Articles