• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why are HashCodes for different Keys the same in a HashMap?  RSS feed

 
Ted Schrey
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to wrap my head around HashCodes. I understand that they are unique integers assigned to objects..and for instance, the HashCode for "cat" is different from "rat". So lets say I create a HashMap called map, and I put in two values with different keys such as: K1 = "Peter", K2 = "Sandra". if I do map.keySet().hashCode() print with at for loop, the HashCode for the different Keys are the same. Why is this? I would think that since the Keys are String Objects, they would have different HashCodes?

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37507
551
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ted,
Welcome to CodeRanch!

This is printing the hash code of the set that contains the keys, not the individual keys:


Try this instead:

 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well map.keySet().hashCode() will return the hashcode of the keyset object, not the keys in the keyset. If that really is what you're calling then you will get the same value each time you call it.

However there is nothing stopping any two different objects having the same hashcode. Hashcode algorithms are designed to limit the possibility that two logically different objects will have the same hashcode, but the contract of the hashcode doesn't require that. It only requires that logically equal objects have the same hashcode.

And when you think about it, there has to be instances of different objects with the same hashcode. There are a finite number of hashcode values available, and an infinite number of potential objects.
 
Ted Schrey
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!