数据结构
JDK1.7数组+链表
JDK1.8数组+链表+红黑树
为什么使用链表
产生Hash冲突的常见做法有两种拉链法和开放定址法。Java中的HashMap使用拉链法。
为什么使用红黑树
链表随着元素的增加平均查找次数线性增加。红黑树是一种平衡树。在平衡的情况下查找次数为logn次。
常见方法解析
put
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
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) { // existing mapping for 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;
}
- 传入key+value
- 通过计算key的hash值来定位数组下标
- 数组中没有元素则直接放入
- 数组中存在元素则取出元素
- 若元素是TreeNode,当前是红黑树,则按照红黑树的方式放入当前节点
- 若不是TreeNode,则使用链表的方式,若链表个数达到8个则变成树
get
get方法就比较简单了。
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))))
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;
}
- 先获取hash值
- 定位数组元素
- 若为树则按照树的方式查找
- 若非树则按链表的方式
size
HashMap有一个modCount变量来记录数据变化,在put、remove的时候会变化这个变量。
HashMap常见问题
为什么HashMap的大小为2的幂次
(n - 1) & hash
n代表数组大小。等价于n%hash,但是不等效。若非2的幂次如15,最后以为永远是0,无法使用造成一定的浪费。
为什么HashMap在多线程下会产生环
在多线程的情况下进行put操作。当达到上限后数组会进行扩容。扩容的时候会使用resize方法。将会创建新的数组,旧数组元素需要移动到新的数组中。例:A、B线程同时触发resize,A将节点放入到新的数组中,B不知道节点已经移动,再次放置。导致节点的相互引用产生了环。