在解决哈希冲突时有一种方法叫链地址法,就是把相同key的value用链表串起来。那么,当用这些相同的key取值时,会得到这个链表,可是链表里有多个值,要返回哪一个值给用户?
3 回答
牛魔王的故事
TA贡献1830条经验 获得超3个赞
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && //检查第一个Node是否性相等
((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) //红黑树中查找
return ((TreeNode<K,V>)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;
}源码是通过hash和equals比较返回的
添加回答
举报
0/150
提交
取消
