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?
John de Michele
Joined: Mar 09, 2009
I just checked the Java API doc, and it doesn't mention any requirement to override equals() or hashCode().
Joined: Feb 22, 2009
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.
Joined: Oct 13, 2005
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.