Monday, February 7, 2011

Why hashCode() can return the same value for different objects in java?

Hai guys i have some interesting thing related to the HashCode of java Objects....

                     The point is that hashcodes can be the same without necessarily guaranteeing that the objects are equal, because the "hashing algorithm" used in the hashCode() method might happen to return the same value for multiple objects"

Q. Do all the Objects of the same class will have the Same HashCode?
A. No

Q. Can different objects can have the same HashCode?
A. May or may not

                  Just consider a  scenario where i am using the HashSet which uses the Hash code to store the  Objects of any class, if i am adding the two different objects which have the same hashCode  and don't forget that  HashSet will not allow the duplicate elements and specifically it uses the hashcode to store and access???????


Typically, this does not produce any problems, because hashCode() is mostly used together with equals(). For instance, a HashMap will call hashCode() upon its keys, to know whether the keys may already be contained in the HashMap. If the HashMap does not find the hash code, it's obvious the key is not contained in the HashMap yet. But if it does, it will have to double-check all keys having that same hash code using equals().
I.e.
A.hashCode() == B.hashCode() // does not necessarily mean
A.equals(B)
but
A.equals(B) // means
A.hashCode() == B.hashCode()
if equals() and hashCode() are implemented correctly

No comments:

Post a Comment