/**
* HashMap:散列链表结构
* HashMap的put方法,源码分析:
* @param key [description]
* @param value [description]
* @return [description]
*/
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
// 1.当key等于null时,把他的value传入putForNullKey方法
if (key == null)
return putForNullKey(value);
int hash = hash(key);
// 7.获取数组的索引值
int i = indexFor(hash, table.length);
// 9.循环进行对比,添加进来的key和已经存在的entry的key是否相同,相同进行覆盖操作
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
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;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
// 2.遍历entry,通过entry获取的key来跟null比较,如果等于null;进行赋值操作.
private V putForNullKey(V value) {
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++;
addEntry(0, null, value, 0);
return null;
}
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
// 8.hash值&上最大索引值
/**
* 这样做的好处是防止索引越界
* 例如:
* 最大索引是:9
* hash是:12
* 进行相&,换算成2进制
* 0000 0000 0000 0000 0000 0000 0000 1001
* 0000 0000 0000 0000 0000 0000 0000 1100
* -----------------------------------------
* 0000 0000 0000 0000 0000 0000 0000 1000
* =8
* 不管hash多少获取的最大索引数都是9
*
*/
return h & (length-1);
}
void addEntry(int hash, K key, V value, int bucketIndex) {// 10.
if ((size >= threshold) && (null != table[bucketIndex])) { // 3.长度大于阈值(总容量*0.75)并且table[bucketIndex]不等于null
resize(2 * table.length);// 进行扩容
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
void createEntry(int hash, K key, V value, int bucketIndex) { // bucketIndex:数组的索引值
// 11.如果 table[bucketIndex]之前不存在,那么Entry就会是首节点,下面的结构会是数组;如果已经存在会形成链表结构,后添加的在链头
Entry<K,V> e = table[bucketIndex];
/**
* Entry的构造:
* Entry(int h, K k, V v, Entry<K,V> n) {
* value = v;
* next = n;
* key = k;
* hash = h;
* }
*
*/
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
void resize(int newCapacity) {
// 4.进行一系类变量赋值操作
// static final int MAXIMUM_CAPACITY = 1 << 30;
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) { // 如果oldCapacity等于MAXIMUM_CAPACITY
threshold = Integer.MAX_VALUE; // 赋值为 231-1 的常量,它表示 int 类型能够表示的最大值。
return;
}
// 5.否则进行原来阈值的2倍扩容
Entry[] newTable = new Entry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
// 6.都是扩容操作不多说了
void transfer(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;
}
}
}