I am analyzing the source code of the HashMap
in Java and asking a question about the put
method.
The following is the put
method in JDK1.6:
public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; }
I got confused in if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
Why such a condition?
Since there is a hashCode
and equals
contract in the Java Object
superclass:
If two objects are equal in accordance with the equals (Object) method, then calling the hashCode method for each of the two objects should give the same integer result.
So, from key.equals(k)
follows key.hashCode() == k.hashCode()
.
hash()
is below:
static int hash(int h) {
thus key.hashCode() == k.hashCode()
implies e.hash == hash
.
So, why not a condition like if ((k = e.key) == key || key.equals(k))
?
source share