There's a relation between the equals() and the hashCode() methods for a class. The rules are briefly as follows: When two objects referred to by variables 'a' and 'b' are to be considered equal, then a.equals(b) == b.equals(a) == true, and a.hashCode() == b.hashCode().
If you write the equals() and hashCode() methods in such a way that this does not hold, then you will get strange bugs if you put those objects in a HashSet or if you use them as keys in a HashMap.
It's always a good idea, if you override equals(), to also override hashCode() in such a way that the above rule is satisfied.
hashCode() is used in cases where the object is being used as a key in the map. And the equals() is used to check for equality of objects. If the objects are equal then their hashCode has to be equal and if their hashCode is equal it doesn't necessarily mean the equals() should be true.
Please SearchFirst to get a lot of replies on similar queries.
An important point is that you never know, at the time you write it, how your class is going to be used in the future (if you're writing anything that isn't trivial). So it's irrelevant whether you are planning to use it in a HashMap or a HashSet or any other specific collection type. It might get used that way in the future. And whoever is using it in the future (you or anyone else) is entitled to assume that you've implemented it correctly. So that means yes, you do need to override hashCode() when you override equals(). If you don't then you are deliberately deciding to break the contract as specified for the equals() method.