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
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With