HashMap数据结构
static final int DEFAULT_INITIAL_CAPACITY = 16;
public V put(K key, V value)
{
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<K, V> e = table[i]; e != null; e = e.next)
{
Object k;
//如果目标Entry和要添加到key是同一Hashcode,或者要添加的key和Entry的key的equals方法返回结果相同,就替换,return。
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);
//i是要添加到Entry的数组的下标
return null;
}
void addEntry(int hash, K key, V value, int bucketIndex)
{
Entry<K, V> e = table[bucketIndex];
//添加节点,链表结构
table[bucketIndex] = new Entry<K, V>(hash, key, value, e);
if (size++ >= threshold) //判断容量,增加容量
resize(2 * table.length);
}
欢迎指正,欢迎交流,热烈欢迎