源码和解析如下所述
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 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
// 1、待查找的数据为对应桶的首节点
return first;
if ((e = first.next) != null) {
// 2、待查找的数据不为对应桶的首节点
if (first instanceof TreeNode)
// 2.1 节点为红黑树,从红黑树中获取对应数据
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
// 2.2 节点为链表节点,遍历链表,从中获取对应数据
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
问题
- 获取数据的大致流程?
(1)计算数据在桶中的位置((tab.length- 1) & hash(key))
(2)通过hash值和key值判断待查找的数据是否在对应桶的首节点,如果在,则返回对应节点数据;否则判断桶首节点的类型。如果节点为红黑树,从红黑树中获取对应数据;如果节点为链表节点,则遍历链表,从中获取对应数据