Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can hashCode() have dynamically changeable content?

Tags:

java

In my implementation, I have a class A which overrides equals(Object) and hashCode(). But I have a small doubt that is, while adding the instance of A to HashSet/HashMap the value of the hashCode() is x, after sometime the value of the same hashCode() changed to y. Will it effect anything?

like image 445
Jessu Avatar asked Dec 13 '22 13:12

Jessu


1 Answers

The hash code mustn't change after it's been added to a map / set. It's okay for it to change before that, although it generally makes the type easier to work with if it doesn't change.

If the hash code changes, the key won't be found in the map / set, as even if it ends up in the same bucket, the hash code will be changed first.

like image 99
Jon Skeet Avatar answered Dec 30 '22 08:12

Jon Skeet