permaculture playing cards
The moose likes Beginning Java and the fly likes Using HashSets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Using HashSets" Watch "Using HashSets" New topic

Using HashSets

Chuck Mondi
Ranch Hand

Joined: Oct 14, 2008
Posts: 31
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
Posts: 600
I just checked the Java API doc, and it doesn't mention any requirement to override equals() or hashCode().

Ryan Beckett
Ranch Hand

Joined: Feb 22, 2009
Posts: 192
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.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
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.
I agree. Here's the link:
subject: Using HashSets
It's not a secret anymore!