Below is the source code of Java 7's HashMap
implementation (get()
method). As you can see, in the the get method, when comparing keys, it compares both the keys' hashcodes and keys' values in order to determine if the entry in the linkedlist is the key searching for. However, I suppose that if two keys are the same, they will of course have the same hashcode, and if two keys are different, comparing the keys' values is enough to differentiate them. So why does the Java HashMap
source code care about the equality of keys' hashcodes?
public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}