您的位置:首页 > 其它

HashMap源码学习(二)

2020-05-11 04:08 351 查看

HashMap源码学习(二)

HashMap get源码分析

public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

/**
* 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) {
//传入hash值,已经确定数据在数组中的位置
//下面只需要判断是不是第一个数据,
//不是就判断数据类型
//是树按照数的方法得到
//是链表就按照链表的凡是得到。
Node<K,V>[] tab;//定义接收数组 tab
Node<K,V> first, e;//定于first键值对,
int n; //定义接收的数组长度
K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//table赋值给tab (table是要获取的hashmap) 判断数组不为空,长度大于零
//第一个数组元素不为空。
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
//这里判断是不是第一个元素,
return first;
if ((e = first.next) != null) {
//判断first后没有没有元素,没有就只是元素。否则后面有元素。
if (first instanceof TreeNode)
//判断first是不是树结构
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//通过.getTreeNode(hash, key)查询到数结构里的数据
do {
//不是数组结构和数结构,就是链表结构,对链表结构遍历,查询hash值和key值相同的找到返回e
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
qintaipeng 原创文章 8获赞 0访问量 198 关注 私信
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: