(1)getEntry(Object key) 方法:
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : 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 != null && key.equals(k))))
return e;
}
return null;
}
根据key的hash值计算出索引,得到table中的位置,然后遍历table处的链表
for(Entry<k,v> e = table[indexFor(hash, table.length)]; e!=null; e=e.next())
对比e的hash,并且判断k是否相等(== || equals)
这是因为即使具有相同的hash值,也不能代表两个完全相等
需要采用equals进行判断
(2)put(K key, V value) 方法
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;
}
步骤:
hash(key.hashcode())->table[indexFor(hash, table.length)]->loop the linkedlist
->(has the key)cover the value
->(not foud key)addEntry
(3)addEntry
(4)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()方法得值再加hash计算得出
(5)map中比较类的equals和hashcode关系
重写equals方法,一定要重写hashcode,要确保如果equals相等,hashcode要一致,因为关系到indexFor在table下的数组位置
但是如果equals不相等,hashcode也可能相等,这就是会造成冲突