In real-life hashing, it’s not uncommon to have more than one entry in a bucket.
The default hashCode method in class Object virtually always comes up with a unique number (hashcode) for each object
ikneet singh wrote:
In real-life hashing, it’s not uncommon to have more than one entry in a bucket.
which bascially means that two objects can have same hashcode
ikneet singh wrote:
The default hashCode method in class Object virtually always comes up with a unique number (hashcode) for each object
which contradicts the above quote.
is the word "virtually" playing some trick here??
Even if the two instances happen to hash to the same bucket, the get()
method will almost certainly return null, as HashMap has an optimization that
caches the hash code associated with each entry and doesn’t bother checking for
object equality if the hash codes don’t match.
Effective Java wrote:
Suppose you attempt to use this class with a HashMap:
At this point, you might expect m.get(new PhoneNumber(707, 867, 5309)) to
return "Jenny", but it returns null. Notice that two PhoneNumber instances are
involved: one is used for insertion into the HashMap, and a second, equal, instance
is used for (attempted) retrieval. The PhoneNumber class’s failure to override
hashCode causes the two equal instances to have unequal hash codes, in violation
of the hashCode contract. Therefore the get method is likely to look for the phone
number in a different hash bucket from the one in which it was stored by the put
method.
Even if the two instances happen to hash to the same bucket, the get()
method will almost certainly return null, as HashMap has an optimization that
caches the hash code associated with each entry and doesn’t bother checking for
object equality if the hash codes don’t match.
ikneet singh wrote:why return null if the bucket is same ? can't equals() method be used instead to match the objects in the bucket ?
what is this "optimization" and "caching" that the HashMap will carry out ? Will all hash based collections work out this optimization ?
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Consider Paul's rocket mass heater. |