Meaningless Drivel is fun!
The moose likes Java in General and the fly likes HashMap and 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 "HashMap and HashSet" Watch "HashMap and HashSet" New topic

HashMap and HashSet

Sudhanshu Mishra
Ranch Hand

Joined: May 28, 2011
Posts: 235

Hi all,
I just read that two different objects can also have the same hashcode.
I have two question(assuming i have overridden hashCode( and equals())
1.Do we save objects of a particular class only in a given collection,or a collection can store any object of any class,
2.If a collection can store any object from any class,and i am using a HashMap for storing the objects,then what if i get the same hashcode values for the two objects?Then how will i save them?


Alexander Kober
Ranch Hand

Joined: Aug 05, 2011
Posts: 32

The agreement is that objects which are equal have to provide the same hash code. Objects that have the same hash code, however, do not have to be equal.

You can store objects which have the same hash code in a HashSet or HashMap just fine. If they are equal, the second instance added will replace the first one. If the objects are not equal, you'll get what's called a hash collision. The map or set implementation will then take care of handling the second object appropriately, for instance by associating every used hashcode with a linked list holding all the non-equal objects with this hashcode.

You can run the following example yourself. Note that i have overridden hashCode in both Example classes to return a constant, something you obviously never want to do in the real world.

I agree. Here's the link:
subject: HashMap and HashSet
It's not a secret anymore!