HashMap
数据结构
数组 + 链表/红黑树
重要属性
/** * 结点冲突数达到8时,就会对哈希表进行调整,如果table容量小于64,那么会进行扩容, * 如果不小于64,那么会将冲突数达到8的那个单链表调整为红黑树. */
static final int TREEIFY_THRESHOLD = 8;
/** * 如果原先就是红黑树,resize以后冲突结点数少于6了,就把红黑色恢复成单链表 */
static final int UNTREEIFY_THRESHOLD = 6;
/** * 如果table的容量少于64,那么即使冲突结点数达到TREEIFY_THRESHOLD后不会把该单链表调整成红黑数,而是将table扩容 */
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 数据表(数组+链表结构),第一次使用的时候才初始化,在通过构造方法初始化HashMap的时候不会初始化table,基本最后都是在 * resize()扩容方法中进行初始化,或者在反序列化中初始化
* 数组的长度永远是 2的平方
* transient 修饰,序列化时不会序列化整个table对象,与List的序列化相似,都是循环遍历逐个序列化数据和链表中的元素
* Node类定义链表的节点,实现了Map.Entry接口,与LinkedList 中不同的是,HashMap的链表是单向链表,Node中只定义了一个指向下一个节点的Next对象,没有定义指向上一个节点的prev对象
*/
transient Node<K,V>[] table;
/**
* 指向内部迭代器对象,在调用entrySet() 方法时会初始化该引用对象,但是该对象并不持有数据,只有当我们在使用增强for循环时才会调用该迭代器,才会输出我们想要的内容
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* 集合中元素个数
*/
transient int size;
/**
* 与List 中的modCount 作用是一致的,是一种fail-fast 机制
*/
transient int modCount;
/**
* 当size >= threshold 时会调用resize 方法进行扩容,即下一个需要扩容的阈值
* 正常情况下 threshold = loadFactor * capacity
*/
int threshold;
/**
* 加载因子,用于计算扩容阈值
*/
final float loadFactor;
- 为什么集合的容量要设置为2的幂
- 当数组长度为2的n次幂的时候,不同的key算得得index相同的几率较小,那么数据在数组上分布就比较均匀,也就是说碰撞的几率小,相对的,查询的时候就不用遍历某个位置上的链表,这样查询效率也就较高了
重要方法
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; // table 为空时会进行扩容,初始化table
if ((p = tab[i = (n - 1) & hash]) == null) // 计算新增元素的在数组集合中的位置 i,如果该位置为空,则将新元素封装为新的节点,并存入这个位置
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) // 如果新增元素是 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) // 如果链表的长度 大于树化阈值,则将链表结构转行为树
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break; // 如果新增元素已经存在于链表中则跳出循环
p = e; //继续对链表中的下一个节点做匹配
}
}
if (e != null) { // 链表中已存在该元素对于的key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value; // 覆盖更新
afterNodeAccess(e); // 钩子,可继承HashMap 实现自己的方法
return oldValue;
}
}
++modCount;
if (++size > threshold) // 判断是否需要扩容
resize();
afterNodeInsertion(evict); // 钩子,可继承HashMap 实现自己的方法
return null;
}
-
流程图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6XPfbqcJ-1608463720645)(F:\学习笔记\note_x\4-java-base\集合\hashMap-put.png)]
-
链表结构转化为红黑树, 什么时候转化,为什么?
- 当链表的长度大于树化阈值的时候,默认是8
- 链表太长时,线性遍历影响检索效率,红黑树通过二分查找的方式可以提高查询的效率
-
红黑树的创建 过程
- 校验是否达到树化的标准 : 如果table容量小于64,那么会进行扩容, 如果不小于64,那么会将冲突数达到8的那个单链表调整为红黑树.
- 将原来的单向链表转化为双向链表
- 将双向链表构建为红黑树
get
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) { // 判断集合是否为空,计算key在数组中的位置
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k)))) // 如果查询元素的hash,key 和 数组中的hash,key一致,则认为是匹配的,返回元素
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;
}
- 红黑树遍历 : 二分查找
resize
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) {
// 旧容量不为空,即存在数据
if (oldCap >= MAXIMUM_CAPACITY) {
// 容量已经是最大容量时,扩容阈值为Integer 最大值,并且不再进行扩容操作,直接返回旧集合
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 扩容后新容量为旧容量的一倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // 如果旧的容量大于默认的容量,则新的扩容阈值为原来的一倍
}
//在调用构造方法时如果指定initialCapacity则threshold会被赋值,如果不指定则threshold为0, 如果构造时指定了initialCapacity 则threshold 作为table 的实际大小
else if (oldThr > 0)
newCap = oldThr;
else { // 未初始化时,用默认的值初始化容量和扩容阈值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 调用构造方法时指定了initialCapacity的情况下,计算新的扩容阈值
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; // table 指向新的容器
// 如果旧数据不为空,则需要将旧数据搬到新的容器中
if (oldTab != null) {
// 遍历旧table 中的元素
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null) // 如果该元素不是链表节点,则计算在数组中的位置,并放入数组中
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode) // 如果是红黑树则拆分树
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order 链表节点拆分,会将一条链表拆分成两条
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);
// 如果lo 链表不为空,则将其挂到新table 的 j 位置
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 如果hi 链表不为空,则将其挂到新table 的 j+oldCap 位置
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
LinkedHashMap
概述
LinkedHashMap 继承了HashMap, 底层的实现都是通过HashMap 来实现,与HashMap 的区别是,LinkedHashMap 维护了一个双向链表, LinkedHashMap 覆写了HashMap 的创建节点方法 newNode,创建节点时,维护节点上一个节点指向和下一个节点指向
重要属性
/**
* 头节点
*/
transient LinkedHashMap.Entry<K,V> head;
/**
* 尾节点
*/
transient LinkedHashMap.Entry<K,V> tail;
/**
* 访问顺序,默认是false,对链表的顺序不做修改,和插入顺序一致
* 如果设置为 true, 则每次对元素进行访问后,该元素将会被移动到链表尾部
*/
final boolean accessOrder;
重要方法
// 重写了hashMap 的 newNode 方法
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
LinkedHashMap.Entry<K,V> p =
new LinkedHashMap.Entry<K,V>(hash, key, value, e);
linkNodeLast(p);// 维护节点的双向指针
return p;
}
// 维护节点的双向指针
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
LinkedHashMap.Entry<K,V> last = tail;
tail = p;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
}
// 遍历,由于维护了一个双向链表,遍历的时候不需要像HashMap一样进行双层for循环先遍历数组再遍历链表
// 同时默认情况下确保了遍历结果的顺序和插入顺序是一致的,而HashMap是不可保证这个顺序的
public void forEach(BiConsumer<? super K, ? super V> action) {
if (action == null)
throw new NullPointerException();
int mc = modCount;
for (LinkedHashMap.Entry<K,V> e = head; e != null; e = e.after)
action.accept(e.key, e.value);
if (modCount != mc)
throw new ConcurrentModificationException();
}
// 重新get方法
public V get(Object key) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)
return null;
if (accessOrder) // 如果设置了访问顺序,则调整该节点在链表中的顺序
afterNodeAccess(e);
return e.value;
}
// 将节点移到链表尾部
void afterNodeAccess(Node<K,V> e) {
LinkedHashMap.Entry<K,V> last;
if (accessOrder && (last = tail) != e) {
LinkedHashMap.Entry<K,V> p =
(LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a != null)
a.before = b;
else
last = b;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
tail = p;
++modCount;
}
}