Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hash Code

 
Tanzeem Akhtar
Greenhorn
Posts: 9
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, well i am unable to understand that why it is mandatory to have same hash-code, if two objects are same?

Thanks in advance.
 
Henry Wong
author
Marshal
Pie
Posts: 21112
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Tanzeem Akhtar:
Hi, well i am unable to understand that why it is mandatory to have same hash-code, if two objects are same?

Thanks in advance.


Short answer... It mandatory because that is the contract.

Longer answer... The way the hash set and map works is to only check for equality in the bucket that it is hashed to. Hashing has an order of one because it doesn't compare with all the objects in the collection, just with the ones in the bucket, which should be near zero items.

This means if two objects are hashing to different buckets, they won't even get compared -- it is assumed to be not equal.

Henry
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic