privatevoidinflateTable(int toSize){// Find a power of 2 >= toSize// 将数组容量变为-->大于传入数组容量的最小的2的整次幂,若传入容量为15,则新的容量为16int capacity =roundUpToPowerOf2(toSize);//临界值= 数组总容量*装载因子
threshold =(int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY +1);//创建新数组
table =newEntry[capacity];//判断是否需要再次获取hash值initHashSeedAsNeeded(capacity);}
确定扩容后容量大小
//例如:number=7,则经过roundUpToPowerOf2后得到的capacity值就为8;number=9,计算后的值为16;number=8,则计算后的值不变为8//保证每次扩容后都为2的幂次方privatestaticintroundUpToPowerOf2(int number){// assert number >= 0 : "number must be non-negative";return number >= MAXIMUM_CAPACITY
? MAXIMUM_CAPACITY
:(number >1)?Integer.highestOneBit((number -1)<<1):1;}
Key为空,放在table[0]
privateVputForNullKey(V value){//遍历table[0]的链表,如果存在key相同的则覆盖for(Entry<K,V> e = table[0]; e !=null; e = e.next){if(e.key ==null){V oldValue = e.value;
e.value = value;
e.recordAccess(this);return oldValue;}}
modCount++;//哈希值为0,如果找不到对应的key,则插入链表addEntry(0,null, value,0);returnnull;}
voidtransfer(Entry[] newTable,boolean rehash){int newCapacity = newTable.length;//遍历整个数组加链表,将旧数组中的数据转移到新数组for(Entry<K,V> e : table){while(null!= e){Entry<K,V> next = e.next;if(rehash){
e.hash =null== e.key ?0:hash(e.key);}//重新获取地址索引int i =indexFor(e.hash, newCapacity);//采用头插法,在这里,将旧的链表转移后的会变成倒序
e.next = newTable[i];
newTable[i]= e;
e = next;}}}
获取hash值
finalinthash(Object k){int h = hashSeed;if(0!= h && k instanceofString){returnsun.misc.Hashing.stringHash32((String) k);}//hasCode进行右移和和异或运算,使得生成的哈希值更具随机性和散列性
h ^= k.hashCode();// This function ensures that hashCodes that differ only by// constant multiples at each bit position have a bounded// number of collisions (approximately 8 at default load factor).
h ^=(h >>>20)^(h >>>12);return h ^(h >>>7)^(h >>>4);}