HashMap实现原理:容量、负载因子、hash与定位都搞定了吗?( 七 )

final Node<KV> getNode(int hash Object key) {
Node<KV>[
tab; Node<KV> first e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash
) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<KV>)first).getTreeNode(hash key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
while ((e = e.next) != null);


return null;

判断元素相等的设计比较经典 , 利用了bool表达式的短路特性:先比较hash值;如果hash值相等 , 就通过==比较;如果==不等 , 再通过equals方法比较 。 hash是提前计算好的;==直接比较引用值;equals方法最有可能耗费性能 , 如String的equals方法需要O(n)的时间 , n是字符串长度 。 一定要记住这里的判断顺序 , 很能考察对碰撞处理源码的理解 。

推荐阅读