Daniel Daniel - 1 year ago 83
Java Question

comparison of hashmap key, why compare both key's hashcode and key's value

Below is the source code of java 7 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;

Answer Source

Testing for int equality with == is a fairly cheap operation compared to invoking equals on a complicated object. The equality of the hashes is a shortcut. If the key isn't there at all, the hashes won't be equal, and a relatively quick == that returns false will save running a costly equals operation (thanks to short-circuit logic). If the key is there, you've just "wasted" another quick equality.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download