(1)HashMap resize()方法 final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
//获取了原容量,如果哈希表为null则返回0,否则返回原长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//获取原来的扩容阈值 int oldThr = threshold;
//定义两个变量保存新的容量和阈值
int newCap, newThr = 0;
//如果原容量长度大于0 if (oldCap > 0) {
//如果原容量大于最大容量,直接返回原哈希表,不在扩容
if (oldCap >= MAXIMUM_CAPACITY) {
//扩容阈值设置为Integer的最大值
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
//使用HashMap无参构造创建对象后,第一次扩容,会执行到此处
//容量赋值为初始容量
newCap = DEFAULT_INITIAL_CAPACITY;
//计算扩容阈值 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//调用HashMap有参构造指定了容量和负载因子后第一次扩容时会执行到次数
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;
//如果原hash表不为null if (oldTab != null) {
//遍历hash表 for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//如果某个位置上有元素 if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//如果这个位置上只是一个Node,没有链表 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 {
// 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;
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;
}
/**
-
源码分析 */ public class MapDemo2 {
public static void main(String[] args) {
Map<Student,String> map = new HashMap<>(); Student s1 = new Student(); Student s2 = new Student(); Student s3 = new Student(); Student s4 = new Student(); Student s5 = new Student(); Student s6 = new Student(); Student s7 = new Student(); Student s8 = new Student(); Student s9 = new Student(); Student s10 = new Student(); Student s11 = new Student(); map.put(s1,"胡卫东"); map.put(s2,"巩晓彬"); map.put(s3,"张卫平"); map.put(s4,"宋小波"); map.put(s5,"宋军"); map.put(s6,"姚明"); map.put(s7,"王治郅");//key为s7时 bincount为6 size为7 map.put(s8,"易建联");//key为s8时 数组长度为16 map.put(s9,"朱芳雨");//key为s9时 进入方法binTree 第一次扩容 16->32 map.put(s10,"杜锋");//key为s10时 第二次扩容 32-64 map.put(s11,"李楠");//该节点添加成功后,转换为红黑树 System.out.println(map.get(s10));
} }
(2)