Monday, February 17, 2014

Hashcode and Equals method usages in Java

Known practice - do not override neither of equals(Object obj) and hashcode() or override them together.
But even after override all of them and implementing properly or even generating code for them by smart tool - there could be a problem.

Advise: All class implementations that override hashcode() and are going to be used in Hashed collections - have to be immutable.

Without following advice above you can end up in situation then you put object in HashSet, change object's field , try to find it in collection by contains() - and you will not find it in collection as hashcode is changed and bucket will be misleading as object is placed in old bucket but hashcode is calculated to point to another bucket (wikivisualization).

Advise: "hashcode()" is Java system related method - do not override it till you have no other choice !!!

Advise: If hashcode() is demand after already overridden "equals(Object obj)" change code to use Comparable or any other approach, it will not cost any time for additional codding but will safe you form problems in future when your systems will be huge.

Reference to other  tools:
HE: Class defines equals() but not hashCode()
HE: Class defines equals() and uses Object.hashCode()
HE: Class defines hashCode() but not equals()
HE: Class defines hashCode() and uses Object.equals()
HE: Class inherits equals() and uses Object.hashCode()



All tool check for methods existence but non of them for immutable state.
Is it on purpose or it is non covered problem of Static Code Analyzers for Java ?

No comments:

Post a Comment