The following is the source code for the implementation of Java 7 HashMap ( get() ). As you can see, in the get method, when comparing keys, it compares the values ββof the hash codes of keys and keys to determine whether the entry in the linked list is a key search. However, I believe that if the two keys are the same, they will certainly have the same hash code, and if the two keys are different from each other, comparing the values ββof the keys is enough to distinguish them. So why does the Java HashMap source code care about hashcodes key equality?
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; }
source share