分析 HashMap 新增元素:(JDK1.7 )
public v put(K key , V value) {
int hash = hash(key) ;
int i= indexFor(hash , table.length);
//该循环通过hashCode返回值找到对应的数组下标位置
//如果equals 结果为true, 则覆盖原值,如果都为 false ,则添加元素
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//如果Key的hash是相同的.那么再进行如下判断
// key是同一个对象或者equals返回为true,则覆盖原来的value值
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;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
//1.7中插入元素时,插入在头部,而不是尾部
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++;
}