首先来一张图
默认初始化容量1<<4 二进制中1左移四位是10000也就是2的四次方=16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
最大容量1<<30 二进制中1左移三十位就是2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;
负载因子 0.75 负载因子*容量就是扩容的阈(yu)值
static final float DEFAULT_LOAD_FACTOR = 0.75f;
链表转换为树的阈值
static final int TREEIFY_THRESHOLD = 8;
少于这个值的时候就用链表
static final int UNTREEIFY_THRESHOLD = 6;
有红黑树时容量小于这个值的时候就resize()(扩容两倍)
static final int MIN_TREEIFY_CAPACITY = 64;
Node就是一个链表,有四个参数,hash,key,value,以及next
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
默认我们创建HashMap()就是用的这个无参构造
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
有参构造(初始化容量和负载因子)
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
>> 和>>>的区别 >>是右移,正数高位补0,负数高位补1
>>>是无符号右移,无论正负都在高位补0
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;
}
假设n=01000000|00000000(n也可以是大于2的14次方小于2的15次方之间的任意数)
00100000|00000000 n>>>1
| 01000000|00000000 n
= 01100000|00000000
最后n就是01111111|11111111 return n+1 也就是10000000|00000000也就是2的15次方
所以这里阈值其实是大于等于(当n=全1时会等于)初始容量最近的2的N次方的值,这里阈值会大于容量值,所以在第一次调用put的时候map容量会扩容成为阈值,然后扩容后的阈值会重新算
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) {
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
最后我们来看put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
调用了putVal方法,其中调用了一个hash(key)方法作为hash
为什么不用key.hashcode()要额外去写一个hash(key)的方法呢?
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
首先分析key.hashCode()得出一个32位二进制数假设为00000000|00000100|10001000|10000000
^符号是异或的意思,任何数异或0等于他本身,本身和本身异或等于0
00000000|00000100|10001000|10001111
^ 00000000|00000000|00000000|00000100(无符号右移16位)
= 00000000|00000100|10001000|10001011
这和数据下标取值有关系,先看putVal方法中tab[i = (n - 1) & hash]
这行代码就是我们的key,value存放地位置,也就是数组的索引值
n我们取默认16,&我们的hash值
假设hash不做处理
(00000000|00000100|10001000|10001011做了处理之后会有些差异)
00000000|00000100|10001000|10001111
& 00000000|00000000|00000000|00001111
= 00000000|00000000|00000000|00001111
也就是高16位可能被屏蔽,即使屏蔽了也可移算出索引值,但是会减少差异性,这就是将性能做到极致的一种表现
然后,为什么我们默认是16呢?
假设是17
那么n-1=16
00000000|00000100|10001000|10001011
& 00000000|00000000|00000000|00010000
= 00000000|00000000|00000000|00000000
无论我们后4位是什么都是0,所以索引只会有两个值,一个是0,一个是16,取16的时候,n-1为1111,那么就会出现0-15种可能,这也是前面定义tableSizeFor要取大于等于容量的最接近2次方数的原因
知道索引怎么算了,再来看看put方法调用的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;
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) treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) {
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;
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;
}
else if (oldThr > 0)
newCap = oldThr;
else {
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;
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 {
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
假设原容量是16
n-1 00001111 2n-1 00011111
& 00010101(hash1) & 00010101
索引值 00000101 00010101 变成101+n
n-1 00001111 2n-1 00011111
& 00000101(hash2) 00000101(hash2)
00000101 索引值 00000101 没有变化
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;
}
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}