wood burning stoves 2.0*
The moose likes Java in General and the fly likes Collections,HashSet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Collections,HashSet" Watch "Collections,HashSet" New topic
Author

Collections,HashSet

V Bose
Ranch Hand

Joined: Jul 10, 2003
Posts: 113
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Collections,HashSet