HashMap的get(Object key)
调用get获取map中的数据,会在源码中调用
getNode(hash(key), key)方法
这个方法把传入的key hash后的key值传入到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) {
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<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;
}
其他中table是整个HashMap,然后把table赋值给tab,判断tab是否为空,为空就直接返回null
(n = tab.length) > 0 tab的长度赋值给n,n是否>0 不大于0 直接返回null
first = tab[(n - 1) & hash]) != null 根据hash后的值取出对应的node,node是空就返回first.hash == hash 取出的值的hash值要等于key的hah值,并且k = first.key) == key || (key != null && key.equals(k)) frish的的key要等于get传入的key,同时他们的equals也要相等 都符合就把first返回回去
如果不符说明有hash值下不止一个node,这时就需要判断这个first是属于红黑树还是链表解构,如果是红黑结构就进入((TreeNode<K,V>)first).getTreeNode(hash, key)方法
如果是链表结构,就直接获取下一个node,判断key相同,并且对应equals也相同