if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
equals相同可以推导出hashCode相同。
那只需要比较equals不就行了,为什么还要比较hash呢?
难道equals相同不能说明hashCode相同吗? 还是hashCode相同不能说明hash相同?
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
equals相等,hashCode一定相等;
换句话说:两个对象hashCode都不同,两个对象就不同,根本没有必要equals了,这样快的多
并且map的put方法是根据hashCode确定添加位置的,如下:
put方法:
用key的hashCode方法计算哈希值,并据此计算出数组下标index
如果没有发生哈希碰撞,则直接放到对应的桶中
如果发生哈希碰撞,且节点已经存在,就替换掉相应的value
如果发生哈希碰撞,且桶中存放的是树状结构,则挂载到树上
如果碰撞后为链表,添加到链表尾
所以put方法要比较hashCode
为了效率。两个大对象的equals比较可能会很耗时间。这里是先比较hash,再检测equals。hash的比较会比equals快很多,因为只是两个数字比较而已。如果hash不同,就不需要equals检测了,节省了时间。
&& 先判断前面条件是否为真,真,后面直接不执行,不同的字符串,hashcode是有可能相同的,根据你提供的hashCode方法获取,比如字符串Aa和BB的hashCode就相同,值却不同。