探究HashMap線性不安全(一)——重溫HashMap的put操作
阿新 • • 發佈:2018-12-12
1 void resize(int newCapacity) {
2 //使用oldTable指向擴容前的table
3 Entry[] oldTable = table;
4 int oldCapacity = oldTable.length;
5 //如果hashMap的容量已經達到最大值,那麼將擴容閾值threshold設定為Integer的最大值
6 if (oldCapacity == MAXIMUM_CAPACITY) {
7 threshold = Integer.MAX_VALUE;
8 return ;
9 }
10 //按照傳入的容量,建立新的table
11 Entry[] newTable = new Entry[newCapacity];
12 //useAltHashing在初始化後為false
13 boolean oldAltHashing = useAltHashing;
14 useAltHashing |= sun.misc.VM.isBooted() &&
15 (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
16 // JVM啟動後,但由於擴容後的容量newCapacity<ALTERNATIVE_HASHING_THRESHOLD,useAltHashing也為false
17 //false與false異或,rehash=false,因此不會對key值重新進行hash計算。
18 boolean rehash = oldAltHashing ^ useAltHashing;
19 //進行新舊table資料的遷移
20 transfer(newTable, rehash);
21 //將table指向遷移後的newTable
22 table = newTable;
23 //按照計算公式為newCapacity * loadFactor更新擴容閾值threshold
24 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
25 }