Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why not to use nonfinal fields to generate hashCode in method HashCode ()

Tags:

java

hashcode

Hi I got suggestion from a coverity(static tool) to use non final fields only in hashCode . Why we cannot use non final fields for generating hashCode. error id is : MUTABLE_HASH_CODE

like image 776
Ajay Avatar asked Dec 04 '25 19:12

Ajay


2 Answers

A hashCode is usually used for a Hash collection such as HashSet or HashMap. If any field changes which alters the hashCode, this will leave the collection in an invalid state.

For this reason, it is preferable that the fields used in hashCode and equals (and compareTo if you have that) only use final fields. The other option is to only use fields which don't change, but this is harder to check for and enforce.

like image 167
Peter Lawrey Avatar answered Dec 06 '25 07:12

Peter Lawrey


The idea is that if two objects are equal they must have the same hashcode. So taken to the next step you could say that an object should always have the same hashcode. Obviously, if you use non-final fields in the hashcode calculation, then the hashcode will not remain the same.

For a more concrete example, if you put an object in a hashmap and then change the object such that the hashcode changes the object in now in the wrong bucket of the hashmap. BAD!

like image 37
John B Avatar answered Dec 06 '25 07:12

John B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!