前提
- jdk1.8之前HashMap的存储方式:链表+hash
- jdk1.8以后中HashMap的存储方式:链表+hash+红黑树算法
作用
- 根据key查找与之一致的对象,并返回对象的value值
业务逻辑整理
- 1,table不能为空,长度要大于0,根据key计算出对应的下标,该下标下的对象不能为空,否则返回空
- 2,该下标对象(frist)的key与查找的可以是否一致,如果一致,则返回当前对象
- 3,frist的下一位对象是否为空,如果为空,则返回空,
- 4,判断frist是否为树结构
- 5,如果为树结构,则调用getTreeNode查找对象
- 6,如果是链表结构,则循环链表,对比key,如果有一致的,则返回该对象,否则返回空
源码分析
get
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
//hash(key) 根据key获取hash值
//getNode根据key,以及hash,查找对应的对象
//如果对象为空,则返回空,如果对象不为空,则返回对象对应的value
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
getNode
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//table不能为空,长度大于0,且hash对应的table数组下标不能为空,否则返回null
//当前返回空,证明要么table为空,要么table数组对应下标的链表(红黑树)为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//如果table数组对应下标元素的key与当前查找的key一致,则返回当前对象
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//否则,判断table数组对应下标元素的下一个对象是否为空,如果为空,则返回空,否则,继续查找
if ((e = first.next) != null) {
//如果为树结构,则getTreeNode查询对象
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//否则,是链表结构,则循环每一个对象,对比key,如果一致,则返回该对象
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}