一、HashMap集合简介
HashMap是java中常用的键值对存储集合,具有有一下特点:
特性 | 描述 |
---|---|
是否允许为null | key和value都可以取值为null |
是否允许重复 | key重复会覆盖,value允许重复 |
是否有序 | 无序 |
是否线程安全 | 非线程安全 |
二、HashMap集合底层的数据结构
1、介绍
- JDK1.8之前HashMap是由数组 + 链表结构组成,数组是HashMap的主体,链表则是主要为了解决哈希冲突(两个对象调用的hashCode方法计算的哈希码值一致导致计算的数组索引值相同)而存在(拉链法:解决冲突)。
- JDK1.8以后(包含JDK1.8)HashMap是由数组+链表+红黑树组成。当链表长度大于阈值(默认为8)并且数组长度大于64时,此时索引位置上的所有数据改为使用红黑树存储。当桶上的节点数小于6则会从红黑树转回链表。
补充:将链表转换成红黑树前会判断,即使阈值大于8,但是数组长度小于64,此时并不会将链表变为红黑树。而是选择进行数组扩容。
这样做的目的是因为数组比较小,尽量避开红黑树结构,这种情况下变为红黑树,反而会降低效率,因为红黑树需要进行左旋、右旋、变色这些操作来保持平衡。同时数组长度小于64时,搜索时间相对要快。所以综上所述为了提高性能和减少搜索时间,底层在阈值大于8并且数组长度大于64时,链表才转换为红黑树。具体可参考treeifyBin方法。
三、HashMap继承关系
● Cloneable 空接口,表示可以克隆。 创建并返回 HashMap 对象的一个副本。
● Serializable 序列化接口。属于标记性接口。HashMap 对象可以被序列化和反序列化。
● AbstractMap 父类提供了 Map 实现接口。以最大限度地减少实现此接口所需的工作。
四、HashMap集合类的成员
1、介绍
// 默认的 table 数组容量 aka 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 默认加载因子为 0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 集合最大容量的上限是:2的30次幂
static final int MAXIMUM_CAPACITY = 1 << 30;
// 链表树化临界值
static final int TREEIFY_THRESHOLD = 8;
// 树转成链表的临界值
static final int UNTREEIFY_THRESHOLD = 6;
// 树化时数组的最小长度
static final int MIN_TREEIFY_CAPACITY = 64;
// 存放元素的数组
transient Node<K,V>[] table;
// 存放元素的缓存
transient Set<Map.Entry<K,V>> entrySet;
// HashMap 中实际元素个数
transient int size;
// HashMap 修改次数,每个扩容和更改map结构的计数器
transient int modCount;
// table 扩容临界值 数组长度 * 加载因子
int threshold;
// table 加载因子
final float loadFactor;
2、loadFactor
- loaderFactor加载因子,用来衡量HashMap满的程度,表示HashMap的疏密程度,影响hash操作到同一个数组位置概率。计算HashMap的实时加载因子的方法为:size/capacity。
- loadFactor太大导致查找元素效率低,太小导致数组的利用率低,存放的数据会很分散。loadFactor的默认值为0.75f是官方给出的一个比较好的临界值。
- 当HashMap中的元素已经达到数组长度的75%时,需要扩容,而扩容涉及到rehash、复制数据等操作,非常消耗性能,所以开发中尽量减少扩容操作,可以通过创建HashMap集合对象时通过指定初始容量来避免。
五、HashMap构造器和常用方法
1、构造方法
(1)无参构造
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
(2)指定初始容量的构造器
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
(3)指定初始容量和加载因子的构造器
如果创建HashMap对象时,输入的数组长度不是2的幂次方,HashMap会通过tableSizeFor方法得到比传递值大且最接近指定大小的2的n次幂的数值。请注意,在jdk8以后的构造方法中,并没有对table这个成员变量进行初始化,table的初始化被推迟到了put方法中,在put方法中会对threshold重新计算。
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0) // 异常:初始容量小于0
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
// 指定容量大于数组最大容量,初始化为最大容量
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor)) // 异常:加载因子小于0 or NaN Not a Number
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
this.loadFactor = loadFactor; // 指定加载因子大小
// 计算 table 的大小,确保为2的n次幂,
// 这里赋值给临界值,在第一次添加元素的时候会初始化为table大小
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
2、put(K key, V value)方法
(1)put方法逻辑流程图
(2)putVal() - 添加元素
/**
* Implements Map.put and related methods.
*
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i; // 定义辅助变量
// 0. 这里是判断table是否初始化,table = null or table.length = 0 初始化table
if ((tab = table) == null || (n = tab.length) == 0) // table:存放元素的Node[]数组
n = (tab = resize()).length; // resize():扩容-数组为空给table初始化16个空间
// 根据key的hash值计算索引值,将table中该索引位置的结点赋值给p,并判断p是否为空
if ((p = tab[i = (n - 1) & hash]) == null)
//若p为null(当前位置没有元素)则创建新的结点Node保存当前要添加的数据,存储到当前索引位置
tab[i] = newNode(hash, key, value, null);
else {
// 这里说明table当前索引位置的结点已经存在数据,下面分情况判断添加元素
Node<K,V> e; K k;
// 1. 判断要添加的元素(key)与table中当前索引位置的Node结点是否相同
// condition: ① hash 值相等 && (② 引用相同 || ③ equals判断相等)
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p; // 元素重复
// 2. 判断当前索引位置元素结点是否是红黑树类型
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 3. 说明当前索引位置结点为链表,且第一个结点与要添加的元素key不同,就遍历链表判断key是否存在
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
// 如果key和链表中所有节点元素都不相同,则添加到链表最后
p.next = newNode(hash, key, value, null);
// 添加元素后判断当前链表是否已经有了8个节点,够8个则将当前链表转成红黑树
// 这里调用treeifyBin()方法会判断table大小是否足够64个,到达64个才会树化
// 不满 64 个空间,会先给 table 扩容
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break; // 退出 for 循环
}
// 如果要添加的元素key在链表中已经存在,则直接退出循环
// condition: ① hash 值相等 && (② 引用相同 || ③ equals判断相等)
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e; // 当前节点后移
}
}
// 要添加的元素 key 已存在,则将重复的元素返回
if (e != null) { // existing mapping for key
V oldValue = e.value;
// 将要添加的 value 替换掉旧值
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount; // 修改次数
// 添加元素成功,table长度加1, 判断是否扩容 数组长度是否大于阈值
if (++size > threshold)
resize();
afterNodeInsertion(evict); // HashMap 没有实现该方法, 供子类实现扩充功能
// return null 表示要添加的元素在table中不存在, 添加成功
return null;
}
(3)treefyBin(): 转化红黑树
/**
* 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 数组的长度是否大于等于 64,未达到则进行数组扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
// 判断当前索引位置结点不为null
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null; // 头尾节点
do {
// 将链表结点转换为树结点类型 TreeNode
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);
}
}
// For treeifyBin
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
(4)resize() - table 扩容
给 table 初始化或者将数组大小翻倍,如果 table 为null,则根据默认值指定初始容量和边界值;否则,因为我们的 table 数组容量是 2 的 n 次幂,所以每个 bin 中的元素一定保持相同的索引,或者在新 table 中移动 2 的 n 次幂的偏移量(元素在新数组中的索引位置为 原来的索引 或者是 原来的索引 + 原容量大小)。
什么时候需要扩容呢:
当HashMap中的元素个数超过数组大小(数组长度*loadFactor)时,就会进行数组扩容。进行扩容操作会伴随着一次重新hash分配,并且会遍历hash表中的所有元素,是非常耗时的。
我们在扩充HashMap的时候,不需要重新计算hash,只需要看原来的hash值新增的bit是1还是0,0的话索引不变,1的话索引变成“原索引 + 旧容量”。
补充:
当HashMap中的其中一个链表对象个数如果达到了8个,此时如果数组长度没有达到64,那么HashMap会先扩容解决,如果已经达到了64,那么这个链表会变成红黑树。
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
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) { // 将新容量和新边界值扩大为原来2倍(<<1 == *2)
// 旧容量已经到达最大容量就扩大临界值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 将容量和临界值扩大2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 将旧临界值赋值给新容量,这里的场景为初始化时使用了带参数的构造器-tableSizeFor()
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 数组初始化
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 这里也是初始化指定容量大小的场景,临界值赋值给容量,这里给临界值重新计算值
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr; // table 边界值更新为新的边界值
@SuppressWarnings({"rawtypes","unchecked"})
// 创建新 table 容量为默认初始容量或之前容量的2倍
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 原数组不为null,说明是扩容-遍历之前的table 赋值给新数组
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) { // 当前索引存在元素 e
oldTab[j] = null; // 方便回收空间
// 1. 当前索引位置只有一个元素,没有下一个结点
if (e.next == null)
// 重新计算当前元素在新table中的索引,将当前索引结点放到新table
newTab[e.hash & (newCap - 1)] = e;
// 2. 当前索引位置有下一个结点,且是红黑树,指定树的操作
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
// 3. 当前索引位置有下一个结点,这里是链表类型
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; // 取出下一个结点
// 扩容核心操作查看:https://www.yuque.com/zhangshuaiyin/java/sv07ip#DYnvE
// 判断当前元素在新数组的索引是否改变
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;
}
3、删除方法(remove)
删除的话首先要找到元素的位置,如果是链表就遍历链表找到元素之后删除。如果是红黑树就遍历树找到之后删除,树小于6时要转成链表。
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index; // 辅助变量
// table 不为空,且指定key的hash计算的索引位置有元素
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v; // 辅助变量
// 1 判断要删除的元素是否是指定索引链表的第一个元素
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
// 2 不是第一个元素,判断链表是否还有其他元素
else if ((e = p.next) != null) {
// 2.1 有其他元素且为树结点
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else { // 2.2 有其他元素,为链表结构
do { // 遍历链表,依次判断要删除的元素的位置
// 根据hash、key的值找到要删除的元素
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break; // 找到,退出
}
p = e; // p 是要删除节点的上一个节点
} while ((e = e.next) != null);
}
}
// 找到元素,执行删除操作
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode) // 树结点删除
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p) // 链表只有一个元素删除
tab[index] = node.next;
else // 链表中有多个元素删除
p.next = node.next;
++modCount; // 计数器+1
--size; // 长度 -1
afterNodeRemoval(node);
return node;
}
}
return null;
}
4、查找元素方法(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;
// 数组不为空,且根据hash计算的索引位置有结点
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))))
return first;
// 不是数组当前索引位置的元素,且有下一个结点
if ((e = first.next) != null) {
if (first instanceof TreeNode) // 树结点
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do { // 遍历链表 找到对应的key
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
- get方法实现的步骤:
- 通过hash值获取key映射到桶。
- 桶上的key就是要查找的key,则直接返回,若不是:
- 如果后续节点是红黑树,通过调用红黑树的方法获取value。
- 如果后续节点为链表,通过遍历链表的形式获取value。
- 红黑树节点调用的是getTreeNode方法并通过树形节点的find方法查找:
/**
* Calls find for root node.
*/
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
/**
* Finds the node starting at root p with the given hash and key.
* The kc argument caches comparableClassFor(key) upon first use
* comparing keys.
*/
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
- 查找红黑树,由于之前添加时已经保证这个树是有序的了,因此查找时基本就是折半查找,效率更高。
- 这里和插入时一样,如果对比节点的哈希值和要查找的哈希值相等,就会判断key是否相等,相等就直接返回。不相等就从子树中递归查找。
- 树的查找时间复杂度为o(logn),链表查找的时间复杂度为o(n);
5、遍历HashMap的四种方式
(1)分别遍历key和value
(2)使用Iterator迭代器迭代
(3)通过get方式(不建议使用)
说明:根据阿里开发手册,不建议使用这种方式,因为迭代两次。keySet获取Iterator一次,还有通过get又迭代一次。降低性能。
(4)jdk8及以后使用Map接口中的默认方法
defalut void forEach(BiConsumer<? super k, ? super V> action)
BigConsumer接口中的方法:
void accept(T t, U u)对给定的参数执行此操作
参数:
t - 第一个输入参数
u - 第二个输入参数
5、HashMap初始化容量
《阿里巴巴Java开发手册》中建议我们设置HashMap的初始化容量(使用HashMap(int initialCapacity))。
为什么要这么建议:
HashMap的扩容条件就是当HashMap中的元素个数(size)超过临界值(threshold)时就会自动扩容。在HashMap中,threshold = loadFactor *capacity。所以,如果没有为HashMap设置初始容量,随着元素个数不断地增加,HashMap有可能发生多次扩容,而HashMap的扩容机制决定了每次扩容都需要重新建立Hash表,非常影响性能。
初始化容量设置多少合适:
《阿里巴巴Java开发手册》有一下建议:
initialCapacity = (需要存储的元素个数 / 负载因子) + 1。负载因子默认为0.75。
六、常见面试问题
1、为什么HashMap的容量为2的幂次方
- 计算索引的效率更高:一般通过%取余的方式不如&的运算性能好。当n为2的幂次方时:hash&(length - 1) == hash % length;
- 扩容时重新计算索引的效率更高: 在上面条件的前提下,HashMap容量为2的幂次方可以使得数据均匀分布,减少hash冲突。hash&oldCap == 0的元素留在原来的位置,否则新位置 = 旧位置 + oldCap。
2、如果两个键的hashCode相同,如何存储键值对
hashCode相同,会通过equals比较key是否相同:
- 相同:则新的value覆盖之前的value。
- 不相同:则将新的键值对添加到哈希表中。
3、何时发生哈希碰撞和什么是哈希碰撞,如何解决哈希碰撞
只要两个元素的key计算的哈希码值相同就会发生哈希碰撞。jdk8前使用链表解决哈希碰撞问题,jdk8之后(包含jdk8)使用链表+红黑树解决哈希碰撞问题。
4、传统hashMap的缺点,1.8为什么引入红黑树?这样结构的话不是更麻烦了吗。
JDK1.8以前HashMap的实现是数组+链表,即使哈希函数取得再好,也很难达到元素百分百的均匀分布。当HashMap中有大量的元素都存放在同一个桶中时,这个桶下有一条长长的链表,这个时候HashMap就相当于一个单链表,假如单链表有n个元素,遍历的时间复杂度就是o(n),完全失去有时。针对这种情况,JDK1.8中引入了红黑树(查找时间复杂度为o(logn))来优化这个问题。当链表长度很小的时候,即使遍历,速度也非常的快,但是当链表长度不断变长,肯定会对查询性能有一定的影响,所以才转成树。
5、为何阈值大于8换成红黑数。
理想情况下随机hashCode算法下所有bin中节点的分布概率会遵循泊松分布,一个链表长度达到8个元素的概率为0.00000006,几乎是不可能事件概率已经非常小了,所以选择了8。由于TreeNodes占用的空间是普通Nodes的两倍,所以需要一定节点数才转为TreeNodes,也是空间和时间的权衡。
参考
- https://www.bilibili.com/video/BV1nJ411J7AA?p=18&vd_source=cd03889ff27e1a185b3e97e3ed96d260