Hashmap key comparison, why compare both the hash code key and the key value

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; } 
+5
source share
1 answer

Testing for int equality with == is a fairly cheap operation compared to calling equals on a complex object. Equality of hashes is a shortcut. If there is no key at all, the hashes will not be equal, and the relatively fast == , which returns false , will save the execution of the expensive equals operation (thanks to the short circuit logic). If you have a clue, you just β€œwasted” another quick equality.

+8
source

Source: https://habr.com/ru/post/1258219/


All Articles