HashMap
针对部分源码进行分析,如果不感兴趣可以直接跳过到面试问题汇总
重要的几个参数:
loadFactor // 因子 用于判断是否需要扩容,默认0.75 threashold = 因子*初始容量 DEFAULT_INITIAL_CAPACITY = 1 << 4 // 默认初始容量 16 TREEIFY_THRESHOLD = 8 // UNTREEIFY_THRESHOLD = 6 // MIN_TREEIFY_CAPACITY = 64
jdk1.8
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;
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);
// 节点数>= 8 了
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;
}
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;
// 原来已经有过table
if (oldCap > 0) {
// 原有的tablelength长度超过最大
// 2^30
if (oldCap >= MAXIMUM_CAPACITY) {
// 将需要扩容的数放到最大 Int.Max_Value 2^31-1
threshold = Integer.MAX_VALUE;
// 不进行扩容,直接返回原表
return oldTab;
}
// 旧表长度扩大2倍要小于 2^30 且 旧表 > 2^4
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// 新tab扩为原来的2倍
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else {
// zero initial threshold signifies using defaults
// 初始化的时候 threashold = 因子*初始容量 用来判断是否需要resize的
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;
if (oldTab != null) {
// 将值 从旧表传到新表
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
// 旧表置空
oldTab[j] = null;
// 此时e只有一个值
if (e.next == null)
// 直接把 e 放到对应位置
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 如果此时e 是树节点说明 后面有很多个节点(红黑树)
// 这里面有个很有意思的,untreeify ,也就是说如果节点数过小(<= 6 )之后会放弃红黑树。改用List
((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;
// 等于0时 将该起点放到原来的索引位置上
if ((e.hash & oldCap) == 0) {
// 尾插法
// 多线程情况下会出现值覆盖的情况
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
// 不等于0 需要将该起点位置 放到 j + 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;
}
红黑树建立
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 如果tab 容量小于 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);
}
}
split() 红黑树调整
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
if (loHead != null) {
// <= 6
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
tablesizefor()
// 获取大于容量的最小2次幂
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;
}
jdk1.7
resize()
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;
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;
}
}
}
HashMap常见问题汇总:
1、HashMap的底层数据结构
1.7 数组 + 链表
1.8 数组 + 链表 + 红黑树
2、HashMap的存储
都会采用计算 key的hashcode,如果存在hash冲突,则会在冲突的节点之后使用链表将数据进行存储。1.8之后的话,如果链表长度超过8,会转为红黑树结构,优化了查询的时间复杂度。
另外,存储过程中如果出现需要扩容的情况(是否需要扩容是依据容量以及影响因子决定(默认0.75)),需要将原先的数组进行扩容。一般扩大为其原始容量的两倍,最大可以扩展到 integer.max_value-1。
resize()过程中,1.7 采用头插法,会将链表倒置。多线程情况下会引起死循环的产生。1.8采用尾插法,多线程情况下也可能产生值覆盖的问题。因此 hashMap是线程不安全的。
3、如果HashMap中链表升级为了红黑树,还有可能转为链表吗?
通过上述的split() 源码我们可以发现这个是有可能的,如果红黑树中的数量 <=6 的话 如果经历resize()会降为 链表
这里需要注意下,节点数>8 不一定是需要升级为红黑树的,可以在源码中看到,如果tab.lengtn <= MIN_TREEIFY_CAPACITY(64)
会进行resize()
4、如果我们设置HashMap初始容量为 5 ,那么HashMap中数组容量是多大?
会取大于5的最小2次幂。原本应该是8 但是由于比默认值还小,所以会取默认值 16
5、既然我们设置的HashMap初始容量不会生效,为什么有些规范中还是要求我们设置默认容量呢?
假设我们需要1024个元素,由于没有设置,需要进行7次扩容,扩容中还需要进行resize(),严重影响性能。
6、HashMap和HashTable的区别
HashMap 线程不安全,HashTable是线程安全的性能较低(方法上很多都加了synchronized)
HashMap 允许key,value 为空,HashTable 不允许key,value为空
关于红黑树:
是平衡二叉树的一种变体
具有以下特征:
根节点是黑色的;
每个叶子节点都是黑色的空节点(NIL),也就是说,叶子节点不存储数据;
任何相邻的节点都不能同时为红色,也就是说,红色节点是被黑色节点隔开的;
每个节点,从该节点到达其可达叶子节点的所有路径,都包含相同数目的黑色节点;