HashMap 特性
- key,value可以为空
- 线程不安全
- 支持快速失败(在for循环中操作remove,put方法时会报ConcurrentModifyException)
HashMap 的几个基本属性值
- loadFactor: 加载因子,loadFactor越大,hashmap的空间利用率越大,反之空间利用率越低.默认值为0.75.
- threshold: 容量阈值,超过该值会触发hashMap的扩容操作.
- capacity: 容量值为2的n的次方值默认值为16
- size: hashMap中包含的node个数
HashMap 的put过程
- 计算index值 index=(n-1)&hash
- 拿到index确定该位置下是否有元素存在,如果不存在则创建一个新的元素赋给该index下,方法结束.
- 如果存在则判断key与hash值与传入的key,hash是否一致,如果一致则根据传入的ifAbsent值是否修改value的值.方法结束
- 如果key与hash不一致,则遍历index对应的链表,如果链表中存在key和hash值与传入的值一致则根据ifAsent值修改value值,如果不在这个的记录,则新建一个新的记录放在链表的最后
- 如果链表的长度超过设定的值,这会将链表结构数据转化为红黑数结构
- 如果size超过threshold值则触发resize操作
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;
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);
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;
}
HashMap resize 过程
/**
* 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;
//计算出Threshold
if (oldCap > 0) {
// 如果老的容量大于等于最大容量则Threshold为整型最大值,并且直接返回hashTable,不进 行扩容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 设置新容量为老容量的两倍且小于最大容量值,并且老容量大于等于默认容量,则新Threshold为之前的两倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 新容量为默认值,threshold为容量的0.75
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值
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) {
// 将hashTable中j位置的值置空
oldTab[j] = null;
// 如果e的next为空,意味着该节点上只有一个元素,不是一条链表
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// 如果e是一个TreeNode则走红黑树的流程
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
// 如果e的next不为空,意味这改节点上是一条链表结构
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;
// e.hash值得最高位为0无需变化
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
// e.hash值最高位为1,位置变为之前位置加上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;
}
问题1: 为什么用(n-1)&hash来计算数据下标值?
这样可以减少hash碰撞.因为n的值是2的n次方,所以除最高位是1外其他位都是0,在与操作的时候不参与运算(任何数与0都为0).所以用n&hash会产生许多相同的值.
问题2: 在多线程执行put方法情况下不会死循环,但会有数据丢失的情况?
在多线程执行的情况下,如果发生hash碰撞,会发生数据覆盖,导致数据丢失.