跳到主要内容

HashMap-查找源码

public V get(Object key) {
Node<K,V> e;
// 同样需要经过扰动函数计算哈希值
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

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 &&
// 计算下标,哈希值与数组长度-1
(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) {
// TreeNode 节点直接调用红黑树的查找方法,时间复杂度O(logn)
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;
}