• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using HashSets

 
Chuck Mondi
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just checked the Java API doc, and it doesn't mention any requirement to override equals() or hashCode().

John.
 
Ryan Beckett
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 50168
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic