//初始化容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//阈值
int threshold;
//修改记录,迭代map时,快速失败
transient int modCount;
2.数据结构
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash;
......
}
3.添加数据put方法
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
//初始化表,重新计算表容量,阈值
inflateTable(threshold);
}
//key为null,直接插入到0的位置
if (key == null)
return putForNullKey(value);
//对key的hashcode,进行了二次hash,尽量减少hash冲突
int hash = hash(key);
//为什么表容量是2次幂,原因就在这了,在查找数组索引时,用的位运算,不是mod
int i = indexFor(hash, table.length);
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;
}
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
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);
}
4.自动扩容,当实际容量大于阈值,并且出现hash冲突时,才会扩容。扩容到原来表2倍。
void addEntry(int hash, K key, V value, int bucketIndex) {
//当table的size大于阈值,并且出现hash冲突时,才会自动扩容
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);
}
5.扩容时最耗时的,因为对原表重新映射到新表。
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;
}
}
}
6.对map迭代时,快速失败 fast-fail 通过比较
final Entry<K,V> nextEntry() {
//当modCount != expectedModCount不等时,直接快速失败!
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry<K,V> e = next;
if (e == null)
throw new NoSuchElementException();
if ((next = e.next) == null) {
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
current = e;
return e;
}
7.rehash时,多线程容易出现环情况。