• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Using HashSets

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 80624
470
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic