HashMap 的get 方法:
//调用get方法返回Entry<K,V>
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
//getEntry方法
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
//对key
int hash = (key == null) ? 0 : hash(key);
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 != null && key.equals(k))))
return e;
}
return null;
}
/**
检索对象进行哈希编码,并将另外一个散列函数应用于结果的哈希码,以防质量差的哈希函数。
这是关键,因为HashMap采用双重哈希表,否则,遇到不同的哈希码不碰撞在较小的Object k。
注:空键总是映射到哈希0,因此索引0
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// 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);
}