HashMap
单个数组元素 桶 —存链表/红黑树
数组 table
一、结构基础
1.1哈希
- 先计算key的hashCode
- 再使用扰动函数(减少哈希碰撞几率 )得到hash值
- (n-1)&hash 当前元素应在的位置
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
1.2 transient Set<Map.Entry<K,V>> entrySet 包含全部键值对的集合
1.3 transient Node<K,V>[] table;
1.4 Node
- K key
- V value
- Node<K,V> nextNode
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
二、常量&变量
- 默认初始容量
2^4 ==> 16
- 最大容量
2^30
- 默认加载因子
0.75
- 树化阈值
当链表长度>=8时(桶上元素),链表转化为红黑树
- 树退化阈值
当树大小<=6时(桶上元素),树退化为链表
- 最小树化容量
64
这里指的是数组长度 小于64扩容 大于等于64树化
当链表长度>=8,且table.length(数组长度)>=64时,才会树化
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
- size hashMap中键值对(映射)的数量
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
- threshold
/**
* The next size value at which to resize (capacity * load factor).
*/
int threshold;
- modCount
修改次数 (hashMap线程不安全,该值相当于一个标志,其他线程修改了Map的结构,这个值就会变化,遍历的时候modCount与预期值不符合,就会报错)
modCount就是HashMap进行结构调整的次数,结构调整就是对键值对数量的改变或者用其他方式改变HashMap的内部结构(比如rehash)。这个实例域用于在属于“HashMap Fail-Fast”的集合视图上生成迭代器。
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
三、构造方法
3.1 带初始容量和加载因子
进行边界情况判断
计算threshold(返回>=给定容量,最小的 ,2的n次方)
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
/**
* Returns a power of two size for the given target capacity.
* 返回大于capacity的 最小的 2的n次方
*/
this.threshold = tableSizeFor(initialCapacity);
}
3.2 带初始容量
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
3.3 无参构造
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
3.4 以其他Map为参数
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
putMapEntries(基础还是putVal)
- 用于构造方法
- 用于putAll
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
四、扩容机制
- 新增元素 旧table为空
- 新增元素 旧map.size()>threshold
4.1 先获取 新容量capacity 新阈值threshold
- 如果之前是非空talbe,新容量为旧容量乘以2
- 如果之前是空table,旧阈值不为0,新容量为旧阈值oldThreshold (前两个有参构造方法,但是初始容量设置为0,threshold通过tableSizeFor计算)
- 如果之前是空table,旧阈值为0,新容量16,新阈值都是用默认值16*0.75(无参构造方法,直接用默认值)
- 新阈值 = 新容量 × 加载因子(超过Max_Capacity 使用 Max_Value)
4.2 重新计算元素在新数组中的位置,然后挂结点
- 树分裂
- 链表
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
// 如果大于最大容量 将threshold设置为最大整数(不会再resize) 不再扩容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 如果没有超过最大值 newCap = oldCap*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// 扩容阈值 乘 2
newThr = oldThr << 1; // double threshold
}
// 如果旧Cap=0 只带容量的构造方法(Cap=0),或双参(Cap=) , 新容量为旧threshold
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 初始容量=0 threshold=0 无参构造方法
// 容量设为默认 16
// 阈值 默认 12 16X0.75
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 计算新的 threshold (新容量×加载因子 再进行一系列判断)
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 至此 各种属性大小已确定 newCap newThreshold
if (oldTab != null) {
// 重新计算元素在新数组的位置 并填进去
// 遍历旧的Map 将旧bucket 转移到 新 bucket
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
// 原位置置空 元素都保存在e中
oldTab[j] = null;
// 遍历e (链表/红黑树)
if (e.next == null)
// 计算新的位置 然后挂上e
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 如果e是树 要拆分
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// e是链表
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
五、其他方法
5.1 新增 单个元素
- 先判断原table 如果是空 resize()
- 再判断计算后 结点位置table[i] 是否有元素 没有直接添加
- 如果有元素 再判断key是否相同,相同进行值覆盖
- key不相同,再判断table[i]是树 还是链表 是树直接按照树的方式挂结点
- 如果是链表,还要判断加上这个结点会不会到达阈值,如果会 树化
- 如果不会,直接在链表尾部加上新结点(遍历到尾部过程中,如果发现相同的key,进行值覆盖) JDK1.7 是在头部插入新结点
- 最后还要判断size是否大于threshold ,如果大于,resize()
- 如果不会,直接在链表尾部加上新结点(遍历到尾部过程中,如果发现相同的key,进行值覆盖) JDK1.7 是在头部插入新结点
- 如果是链表,还要判断加上这个结点会不会到达阈值,如果会 树化
- key不相同,再判断table[i]是树 还是链表 是树直接按照树的方式挂结点
- 如果有元素 再判断key是否相同,相同进行值覆盖
- 再判断计算后 结点位置table[i] 是否有元素 没有直接添加
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
public class A {
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K, V>[] tab;
Node<K, V> p;
int n, i;
// table[] 是空的
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// table[] 不是空 且 目标位置没有元素 直接挂上结点
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 该位置上已经有元素
else {
Node<K, V> e;
K k;
// key值相等 直接覆盖旧值
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// key值不相等
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);
// 0---7 达到阈值 树化 链表长到8-->红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 与链表元素key相同 值覆盖
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;
// 先挂结点 再size+1 size>threshold resize
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
}
5.2 TreeifyBin 树化
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 如果table是空或者table的length(数组长度)<树化阈值 resize()扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}