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
-
2hashcode must not be mutable.xdazz– xdazz2011-10-18 10:12:38 +00:00Commented Oct 18, 2011 at 10:12
-
why Hashcode should not be mutable? If the state of the object changes , then its hashcode may change depending on how significant the state changes are. The argument that it causes problems with objects in hashmap ,its up to the programmer to know the behaviour of his code and code proper safegards if necessary.Bhaskar– Bhaskar2011-10-18 10:39:47 +00:00Commented Oct 18, 2011 at 10:39
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.
1 Comment
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!
8 Comments
equals when called on a object whose state undergoes changes will still and always return true, and it is incorrect to use only non-final fields in equals ( even the hashmap logic does not apply here). To quote your own example , the person after marriage ( and name change ) is indeed different from the pre-marriage person, but equal to self in the post-marriage state.