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.
In my book Head First Java, they explain that you must override the equals() and hashCode() methods from Object in order to use a HashSet. I was also looking at the Deitel Java How to Program book and they don't state that you need to override equals() and hashCode(). Is there a preferred way to using HashSets?
Overriding equals() ensures objects have a way to test equality correctly. It is common to use a String or Integer as a key for a Hashtable, because they both override equals(). If your object doesn't define how to test equality how can the hash structure make the correct comparisons all the time? It won't. Overriding these methods will make sure it does thus improving the performance of the structure. Overriding hashCode() may lessen the chance of two objects hashing to the same value. You can use a more complex hashing algorithm.
Whoever designs a class must decide how its instances are considered "equivalent" or not.. That is implicit in what it says about Object#equals(java.lang.Object) in the API documentation. It says in the java.util.Set documentation that Sets don't contain duplicates. Remember duplicates can only be identified if the equals method is used.
My copy of Deitel (6th edition, page 451) says "a class that overrides equals should also override hashCode", and comments about the overridden equals method at the top of page 910.