get方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
点击getNode方法进入如下代码:
getNode方法
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) { //判断对应的index是否有元素
if (first.hash == hash && //定位到index,判断该元素的key是否相同,用双等号、equals来判断
((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 {
//遍历链表找到给定key对应的节点
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
步骤
1)对key取hash值。
2)将hash值与(n-1)做与运算得到index
3)如果数组中该index位置为null,则直接返回null
4)如果数组中该index位置的元素的key和我传入的key相等(满足双等号和equals一个即可),则返回给元素。否则遍历链表或红黑树。
5)如果该index位置的元素属于红黑树节点,则走红黑树返回该节点。
6)如果该index位置的元素属于链表节点,则遍历链表,与步骤4)中的检索方式一样。