I was reading the paragraph quoted below from an article entitled- Java theory and practice: Hashing it out - Defining hashCode() and equals() effectively and correctly
Defining equality The Object class has two methods for making inferences about an object's identity: equals() and hashCode(). In general, if you override one of these methods, you must override both, as there are important relationships between them that must be maintained. In particular, if two objects are equal according to the equals() method, they must have the same hashCode() value (although the reverse is not generally true).[emphasis added by me]
My question relates to the latter bit of the paragraph "although the reverse is not generally true". How is it possible for two different instances of a class to have the same hashCode but not be equal?
The hashCode contractObjects with the same hash code must be equal – WRONG!
It's perfectly legal for two unequal objects to have the same hash code. It's used by HashMap as a "first pass filter" so that the map can quickly find possible entries with the specified key. The keys with the same hash code are then tested for equality with the specified key.
1) If two Objects are equal according to equal(), then calling the hashcode method on each of those two objects should produce same hashcode. 2) It is not required that if two objects are unequal according to the equal(), then calling the hashcode method on each of the two objects must produce distinct values.
Since, hashmap searches key/value pair based on hashcode of key. Hashmap will find 209 hashcode for key "b". Since, same hashcode is found for key "a", Hashmap may return value "aValue" instead of expected value "bValue". So, here is my question, I want to retrieve value associated with key.
You can consider hashes to be a bucket
..
So, hashcode is nothing but the hash-value for that Bucket.. Any number of objects can have same hashcode, depending upon the algorithm used to calculate the hashcodes..
An ideal algorithm is the one, which generates different hashcodes for different objects. So, there is ideally 1 object
per bucket
.. Of course this is the perfect case, which might not be possible..
A bucket may of course contain several objects, based on some property..
In simple terms hashcode () is a function to generate hash by some formula, so there can be some collisions, two different values can turn out to have same hashcode.
If I simply calculate the hashcode by taking mod by 6, then two different values might be having same hashcode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With