Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections,HashSet

 
V Bose
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wan't to have a collection of Unique Strings.
If I were to use a HashSet, how do I override .hashcode(). What would I use as a hashvalue?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Why would you want to override hashCode()? If you put a bunch of Strings into a HashSet, duplicates will already be removed. The hashCode() method is not used to determine uniqueness, only to "file" the objects in a sensible way.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may have heard that to use a class in a HashSet you need to override its hashCode() and equals() methods. This is often true for classes which you write yourself - the methods inherited from Object often don't do exactly what you need. But when you're using a class written by someone else, especially Sun, there's a good chance that hasCode() and equals() have already been set up correctly for you. You can look in the API for String to see that these methods have already been overwritten in String. There's no need for you to do more.
If you want to learn how to write these methods well for other classes, I recommend getting Effective Java. Only a few pages (25-41) discuss this particular question, but the rest of the book is extremely useful for other things. Strongly recommended.
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to learn how to write these methods well for other classes, I recommend getting Effective Java. Only a few pages (25-41) discuss this particular question, but the rest of the book is extremely useful for other things. Strongly recommended.
Strongly agree. Just the chapters on equals() and hashCode() are worth the price of the entire book. "Effective Java" is one of the very few Java books that I find myself coming back to.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic