构造函数
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);
}
在构造函数用到一个非常巧妙得算法计算最小容量。我们来裂解下这个算法。
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;
}
我们假设这时进来得cap为2次幂,则这个cap得2进制结果应该是
100…00
减一变成
011…11
此时右移一位(001…11)然后进行位或得
011…11
此时右移2位(000…11)然后进行位或得
011…11
同理可得
右移16位后再位或还是得
011…11 再加1就能得到最初得2次幂,而这个2次幂就是这个cap得最小二次幂
第二种情况,当cap不为2次幂时,cap的的二进制结果应该是(不规则的)
01011010
00101101
此时右移一位(00101101)然后进行位或得
01111111
此时右移2位(00011111)然后进行位或得
01111111
此时右移4位(00000111)然后进行位或得
01111111
同理和之前一样最后得到的数据也是一个
01111111… 的数据 再加1自然变成一个二次幂,并也是大于cap的最小二次幂
put方法
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;
//判断数组是否为null,或者数组的大小0
if ((tab = table) == null || (n = tab.length) == 0)
//条件成立的时候进行resize()
n = (tab = resize()).length;
//判断在hash桶的位置有没有元素
if ((p = tab[i = (n - 1) & hash]) == null)
// 不存在就生成一个新的Node
// Node是一个链表
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 进入else 就说明Node节点是存在的
//如果p不等于空,而且p的key和hash和传入的值相等,说明传入的元素key重复
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//判断p是否为TreeNode
else if (p instanceof TreeNode)
//调用putTreeVal
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 如果前面两个条件都不满足,就要开始遍历链表
//binCount用来计算是否将链表转为红黑树
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;
}
// 判断p节点的next节点是否key和传入的key相同
// 如果相同的话,说明key重复了
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// 准备下次循环
p = e;
}
}
//此时拿到 的e是存在相同key值(即传入的key已经在map中存在)
if (e != null) { // existing mapping for key
V oldValue = e.value;
//onlyIfAbsent 为false 或者oldValue 为空
if (!onlyIfAbsent || oldValue == null)
//给e赋值
e.value = value;
//为linkedHashMap提供的
afterNodeAccess(e);
//返回旧值
return oldValue;
}
}
++modCount;
// 判断size是否大于界值
if (++size > threshold)
resize();
//为linkedHashMap提供的
afterNodeInsertion(evict);
return null;
}
resize()
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
//拿到原table的size
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//oldCap >0 说明table已经初始化过,现在是扩容
if (oldCap > 0) {
//判断table的大小
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 给新的table扩容
// 分析下这个判断,首先给新table扩容,然后判断oldCap是不是大于
//DEFAULT_INITIAL_CAPACITY,大于的再给threshold扩容
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//如果上面的if没走进去,说明这个是进行初始化,初始化赋予阈值
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//oldThr 小于等于0 说明调用的是默认构造函数,未传入初始大小
else { // zero initial threshold signifies using defaults
// 进行默认构造
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 如果前面都没给新的threshold赋值,开始赋值
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;
// 开始将oldTab 数据搬移到newTab
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// e.next说明oldTab在该节点只有一个元素,直接搬移到newTab
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//如果是TreeNode,则对treeNode进行搬移
else if (e instanceof TreeNode)
((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;
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;
}
关键点一:
resize() 的时候是如何计算新的table中各元素位置。在这里和大家详细讲一下。
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);
这个代码就是原节点复制到新table中节点逻辑的关键。
在这里会去计算(e.hash & oldCap)==0,
计算e的hash和oldCap的位与
此时要明白oldCap的二进制最高位为1,其他都为0,
所以hash与oldCap位与结果只有0和和oldCap
然后newCap等于2oldCap,newCap定位节点是(2oldCap-1)&hash
如果hash&oldCap位与是0的话,那(2oldCap-1)&hash的值应该和oldCap该节点所在的位置一致。
因为我们知道2oldCap-1和oldCap二进制最高位是一样的.,在进行位与运算时,
(2oldCap-1)&hash = (oldCap&hash)+((oldCap-1)&hash)
能明白这一点 后面就好理解了。
如果hash&oldCap位与是oldCap的话,那(2oldCap-1)&hash的值应该和oldCap该节点再加上oldCap值一致。
get方法
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;
/*
三个判断条件:
1.table不能为空。
2.len>0;
3.能找到相应位桶。
三个条件满足 可以找元素
*/
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//先判断第一个,第一个key和hash值都匹配直接返回
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);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}