Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 355
Daniel Avatar asked Oct 14 '16 15:10

Daniel


1 Answers

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.

like image 63
Mureinik Avatar answered Oct 07 '22 09:10

Mureinik