/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/public V put(K key, V value) {
//如果table表为空,则初始化表,设置极限容量threshold,设置表容量if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//map的key可以为空,默认插入hash值为0的桶处if (key == null)
return putForNullKey(value);
//key非空,则计算其hash值int hash = hash(key);
//计算其在table表中的索引值下标int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
//遍历下标为i的entry链表(next引用模拟指针)//当找到key值相同的entry时,直接将新value替换掉原来的旧value//recordAccess(子类使用如linkedhashmap)
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
//如若插入值新,不存在key已之相等的,则插入entry链表中(next引用模拟指针)
modCount++;
addEntry(hash, key, value, i);
returnnull;
}
/**
* Inflates the table.
*/privatevoidinflateTable(int toSize) {
// Find a power of 2 >= toSize//map capacity容易必须为2的整数次幂 int capacity = roundUpToPowerOf2(toSize);
//计算极限容量threshold为容量*加载因子和最大容量之间比较的最小者
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
//初始化table表
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
// 调用key的hashCode()方法得到hashCode
h ^= k.hashCode();
// 对hashCode进行一系列的位移与异或运算并把结果作为hashCode返回
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
//扩容时重新hash各entry链表void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
//首先将entry链表中的next entry取出来
Entry<K,V> next = e.next;
if (rehash) {
//重新计算该entry链的hash值
e.hash = null == e.key ? 0 : hash(e.key);
}
//计算其在新扩容表中的下标索引值int i = indexFor(e.hash, newCapacity);
//将其next引用指向上一次取出来的entry
e.next = newTable[i];
//将其放置在 newTable[i]中
newTable[i] = e;
//继续将next依次取出来连接之前已经取出来的entry
e = next;
}
}
}
//将新map插入到entry链表中void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}