jdk1.8的HashMap相比JDK1.7,最主要的变化就是引入了红黑树。
HashMap底层是Entry
get(key) :
1、计算key的hash值,找到数组索引下标。
2、如果此处只有一个Entry,直接返回这个值。
3、如果此处是一个链表,则根据hash值和equals方法逐一匹配,一旦匹配上了,就返回结果;如果所有的都是false,则返回空。
put(key,value) :
1、计算key的hash值,找到数组索引下标。
2、如果索引位置是空的,则将Entry放在这个位置。
3、如果索引位置已经存在一个链表,则根据hash值和equals方法逐一匹配,一旦匹配上了,就覆盖value;如果所有的都是false,则将这个Entry放在链表的末尾。
HashMap的常量和参数# 常量,默认初始化容量8 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; # 常量,最大容量 2的30次方 static final int MAXIMUM_CAPACITY = 1 << 30; # 常量,默认负载因子是0.75 static final float DEFAULT_LOAD_FACTOR = 0.75f; # HashMap的实际大小,即key-value键值对个数 transient int size; # 被编辑的次数,新增、删除都会加1, # 这在并发时会有意义,并发条件下,如果有其他线程对这个map同时做了修改, # if (map.modCount != expectedModCount) # throw new ConcurrentModificationException(); # 当前线程在编辑这个map时就会抛出ConcurrentModificationException异常 transient int modCount; # 阈值,即最大容量 int threshold; # 负载因子 final float loadFactor;HashMap的静态内部类
static class NodeHashMap数组的容量总是2的n次方,怎么设置的?implements Map.Entry { # 哈希算法计算后的哈希值存放在这里,不需要每次都去算 final int hash; final K key; V value; # 指向下一个节点的引用 Node next; Node(int hash, K key, V value, Node next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry,?> e = (Map.Entry,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } }
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[] tab; Node 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 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)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;
}
final Node[] resize() {
Node[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
# 此处可以看出新的数组长度是旧数组的两倍
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;
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;
@SuppressWarnings({"rawtypes","unchecked"})
Node[] newTab = (Node[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node 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)e).split(this, newTab, j, oldCap);
else { // preserve order
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node 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);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
为什么要把数组长度设计为2的n次方呢?
final Node getNode(int hash, Object key) {
Node[] tab; Node first, e; int n; K k;
# 此处可以看出,Node在数组中的下标是由位运算 (n - 1) & hash 的结果决定的
# 这里的n就是数组长度
# 根据位运算的逻辑,如果n不是2的幂次方,那么 (n - 1) & hash 的结果很有可能相同
# 这就造成了哈希冲突。
# 为了使计算出来的数组索引尽可能的分散,所以数组长度n被设计为2的幂次方
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)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;
}
HashMap是在声明的时候就开辟内存空间吗?
不是的,在HashMap常规构造器中,只是设置了阈值和负载因子的值,并没有为数组table分配内存空间(有一个入参为指定Map的构造器例外),而是在执行put操作的时候才真正构建table数组。



