Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equals() and hashCode() changes

What problems can arise if the result of the equals() and hashCode() methods changes across the lifetime of an object?

Thank you!

like image 909
yoX64 Avatar asked Mar 18 '23 05:03

yoX64


1 Answers

One problem is that you won't be able to find that object in a HashSet or a HashMap (when that object is a key in the Map) if its hashCode changes after to add it to the Collection.

Changing the result of equals during the lifetime of an object may result in breaking some Collections. For example, you may find you have duplicate objects in your Set, because at the time the second object was added to the Set, they weren't equal.

like image 190
Eran Avatar answered Mar 28 '23 07:03

Eran