This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
We created a custom class to act as a key for HashMap as follows :
The CommonUtils.fieldChanged function is as follows :
When this class is used as a Key in HashMap and retrieve the value, I get a null - although in Debug mode I see the same key present in the HashMap too. I believe that this has got to do something with the equals / hashCode methods. Can anybody point to as what is wrong ?
To work correctly as a key in hash-based collections such as HashMap, your class must indeed have correctly implemented equals() and hashCode() methods. The documentation of the method hashCode() in class Object explains what the contract for this method is. The most important thing to remember from it is that if two objects are equal (i.e. equals() return true), then the hashCode() methods of both objects must return the same value.
In case of your code, the equals() and hashCode() methods seem to be OK - I don't see any obvious problems.
Maybe there is something else in your code, in the rest of the program somewhere, that causes the problem.
Any class being used as a key for a hash map should be immutable (at least as far as the hashcode() and equals() methods are concerned) since any change to a field that is used by either hashcode() or equals() will destroy the lookup of objects in the map. Since the fields in your class can be modified you don't have this property.
Retired horse trader.
Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
The actual bug in your code is that you're calling hashCode() on the HashCodeBuilder (that class doesn't even overwrite the hashCode() method).
The proper usage of HashCodeBuilder is to call toHashCode() after setting it up:
But what James said is indeed also important. Objects that you use as keys in a HashMap must not be mutable, because if you modify the fields after you've put the object in the HashMap, so that the result of hashCode() changes, will confuse the HashMap, so that it can't find your objects anymore.