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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Hash Code" Watch "Hash Code" New topic
Author

Hash Code

Tanzeem Akhtar
Greenhorn

Joined: Sep 11, 2007
Posts: 9

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.


Tanzy..
http://techythought.wordpress.com/
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18108
    
  39

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Hash Code
 
Similar Threads
HashMaps
Regarding Hashcode
equal() method of class Object
Duplicate elements in HashSet
Printing a primitive array