1.HashMap底层实现原理是什么?
HashMap由数组+链表组成,JDK8中新增了红黑树,当链表长度达到8(默认阈值)时,链表转化成红黑树,链表过长对性能有很大的影响。
//HashMap初始化长度
static final int DEFAULT_INITIAL_CAPACITY = 1<<4;//位运算,1左移四位是16
//HashMap最大长度
static final int MAXIMUM_CAPACITY = 1<<30;//1073741824
//默认加载因子(扩容因子)
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;
PS:HashMap构造时可以指定默认初始大小和负载因子,
经典面试题:
1.JDK8中HashMap扩容时做了哪些优化?
JDK8在hashmap扩容时不再重新计算每个元素的哈希值,而是通过高位运算(e.hash & oldCap)来判定元素是否需要移动。
例如:
key1.hash = 10 0000 1010;
key2.hash = 10 0001 0001;
oldCap = 16 0001 0000;(oldCap就是扩容前table.length)
key1.hash & oldCap的高一位为0,扩容时元素下标不变;
key1.hash & oldCap的高一位为1,扩容时元素下标=原下标+原数组长度。
PS:与运算,有0则0,全1则1。
且JDK8新增元素采用的是尾插法(尾部正序插入),而JDK7是头部插入(头部倒序插入),JDK8有效的避免了JDK7在扩容时的死循环和数据丢失的问题,但是仍然存在数据覆盖的问题,这也就是HashMap线程不安全的一部分原因。
2.加载因子为什么是0.75?
加载因子是来判断什么时候进行扩容。
当加载因子设置比较大时,扩容发生的频率比较低且占用的空间会比较小,但这样的话发生hash冲突的几率就会增大,因此需要更复杂的数据结构去存储数据,这样对元素的操作时间增加,运行效率会降低;
当加载因子设置较小的时候,会发生频繁的扩容且占用空间增大,此时hash冲突的可能性就比较小,操作性能会提高
3.当有哈希冲突时,HashMap是如何查找并确认元素的?
当哈希冲突时需要通过判断 key 值是否相等,才能确认此元素是不是我们想要的元素。
4.HashMap源码中有哪些重要的方法?
查询、新增和数据扩容
查询:查询时先比较key的hashcode然后去比较key值,将对应的value值返回;
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);
//循环,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;
}
新增:
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;
//根据key的hash值计算要插入的数组索引i,如果tab[i] == null,则直接插入
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;
else if (p instanceof TreeNode)
//红黑树插入树节点
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//链表结构训话插入,放在链表的尾部(JDK7是插入链表头部)
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) { // 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;
}
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//当整个map中元素个数小于64时,只是进行扩容
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);
}
}
数据扩容:
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) {
//如果已经达到最大容量,只将阈值设置成Integer.MAX_VALUES,返回
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//如果扩容后newCap未达到最大容量且oldCap大于初始大小16
//将阈值变为原来的两倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;
}
//如果oldCap大于代表初始化时用的是HashMap的有参构造
else if (oldThr > 0)
newCap = oldThr;
else {//HashMap的默认构造
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;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//判断原数据不为空,开始将数据转移到新table里面
if (oldTab != null) {
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 {
//链表复制,JDK8扩容优化
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//&运算,如果高一位为0,保持原索引
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
//否则,新索引=原索引+oldCap
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.Hashmap是如何导致死循环的?
JDK7为例
线程1->put(key(3))
线程2->put(key(7))
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next; //假设线程1执行到这里,丢失了CPU使用权
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
当线程1执行到”Entry<K,V> next = e.next;“时,此时e = key(3),e.next = key(7),然后此时CPU使用权被线程2夺取,然后线程2重新rehash,链表顺序被反转,由key(3)->key(7)变成了key(7)->key(3),此时线程1再次获取CPU使用权,接着执行代码,newTalbe[i]=e把key(3)的next设置为key(7),而下次循环时查询到key(7)的next元素为key(3),于是就形成了key(3)和key(7)的循环引用,因此导致了死循环发生。
6.为什么HashMap线程不安全?
https://blog.youkuaiyun.com/swpu_ocean/article/details/88917958
小结:
HashMap并发的情况下本身就不是线程安全的,建议使用ConcurrentHashMap