JavaでソースコードHashMap
を分析し、put
メソッドについて質問があります。なぜHashMap.putはハッシュとテストの平等を比較しますか?
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;
}
は、私はこのような状態であるのはなぜif (e.hash == hash && ((k = e.key) == key || key.equals(k)))
についての混乱:以下
はJDK1.6でput
方法ですか?
のJavaスーパークラスObject
に、hashCode
とequals
のcontractがあるので:
2つのオブジェクトが2つのそれぞれにhashCodeメソッドを呼び出して、等しい(オブジェクト)の方法に従って等しい場合オブジェクトは同じ整数結果を生成する必要があります。
したがって、key.equals(k)
はkey.hashCode() == k.hashCode()
を意味します。
hash()
は以下である:
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20)^(h >>> 12);
return h^(h >>> 7)^(h >>> 4);
}
従ってkey.hashCode() == k.hashCode()
はe.hash == hash
ことを意味します。
なぜ、条件がif ((k = e.key) == key || key.equals(k))
のようになっていないのですか?