HashMap
数据结构:
内部维护一个Node的数组(Node初始时为链表结构,当链接数量大于8后转为红黑树)
定位:
定位节点时,通过key的哈希值和‘&’运算符计算出下标,在Node数组获取元素
//p(所获取Node),tab(Node数组),n(Node数组长度),hash(key计算出的hash值)
p = tab[i = (n - 1) & hash
put:流程如下
- Node数组扩容检查
- 根据形参key在Node数组定位到一个节点(节点为链表或红黑树结构)
- 在该节点中寻找key相同的节点
//table和tab(指Node数组),p(定位到的节点),n(Node数组长度),i(根据key的hash值计算出的节点位置)
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//Node数组扩容检查
n = (tab = resize()).length;
//定位一个节点;判断节点如果为空,则在Node数组里创建一个节点
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k; //e(key和形参key相同的节点),k(e的key)
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode) //判断如果节点为树结构,则调用putTreeVal设置值
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else { //递归Next属性,直到找到Key和形参相同的节点,或者返回空
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // 经过上面的查找,此时e是和形参具有相同key的节点,接下来进行值的修改
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold) //判断如果新增了节点,则进行扩容检查
resize();
afterNodeInsertion(evict);
return null;
get:流程如下
5. 根据Key定位到一个节点(节点是链表结构,或者是树结构)
6. 判断第一个节点
7. 判断红黑树节点
8. 递归寻找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 &&
((k = first.key) == key || (key != null && key.equals(k))))
return first; //判断如果Key相同则返回该节点
if ((e = first.next) != null) {
//如果是红黑树结构的节点,则调用getTreeNode方法获取值
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//递归节点的next值,直到找到Key相同的节点或返回空
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}