核心参数
/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
/**
* The next size value at which to resize (capacity * load factor).
* @serial
*/
// If table == EMPTY_TABLE then this is the initial capacity at which the
// table will be created when inflated.
int threshold;
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
- threhold:实际的负载量,超过了这个值,就会扩容。
- loadFactor:扩容因子。
- 真实容量(capacity) * loadFactor = threhold
- Entry<K,V>[] 这是个Entry<K,V>的数组,代表了整个hash表,其中每一个Entry<K,V>代表一个桶,他是一个链表。正因如此,即使发生了哈希冲突,也可以放在同一个桶中。
- modCount
我们知道HashMap不是线程安全的 , 也就是说你在操作的同时可能会有其它的线程也在操作该map, 用modCount来记录修改集合修改次数。
我们在边迭代边删除集合元素时会碰到一个异常ConcurrentModificationException , 原因是不管你使用entrySet()方法也好 , keySet()方法也好 , 其实在for循环的时候还是会使用该集合内置的Iterator迭代器中的nextEntry()方法 , 如果你没有使用Iterator内置的remove()方法 , 那么迭代器内部的记录更改次数的值便不会被同步 , 当你下一次循环时调用nextEntry()方法便会抛出异常。
一个hashmap的构造
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
让我们来看一下这两个常量是什么
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
两个默认值看到容量为16,负载因子为0.75 ,这也就是一会要赋给的threhold和loadFactor的默认值。
点进构造方法所调用的函数:
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
threshold = initialCapacity;
init();
}
默认容量16,负载因子0.75分别赋给initialCapacity ,loadFactor。
会在首次put时把threshold设置为 16 * 0.75.
put()详解
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
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;
}
如果map是空的,(这个table就是上面提到的Entry<K,V>[] ,)通过inflateTable(threshold)初始化
/**
* Inflates the table.
*/
private void inflateTable(int toSize) {
// Find a power of 2 >= toSize
int capacity = roundUpToPowerOf2(toSize);
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
将原本容量转化成二进制 (向上取整)赋值给了capacity,作为实际容量,如 7转化成8 9转化成16。(有个小疑惑,为什么要这么做呢)看下roundUpToPowerOf2()函数
private static int roundUpToPowerOf2(int number) {
// assert number >= 0 : "number must be non-negative";
return number >= MAXIMUM_CAPACITY
? MAXIMUM_CAPACITY
: (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
}
然后将threshold 变成了 新的容量 capacity 的loadFactor(扩容因子)倍 。
第一次put时会初始化数组,其容量变为不小于指定容量的2的幂数。然后根据负载因子确定阈值。显然易见的负载因子可以更改。如果能力足够的话。(反正暂时我还是做不到)
继续往下进行 ,如果key值为空那么又进入到一个方法
/**
* Offloaded version of put for null keys
*/
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;
}
这个方法所代表的含义就是,查看整个hash表的第一个桶(是个链表),看这个链表中有没有键值为空的,如果有,就将val赋值给它。并返回原来null代表的value。否则进入addEntry方法
/**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/
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);
}
如果没有负载,即threshold没有满并且桶中为空则进入到createEntry方法
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++;
}
在当前桶中头插入这个节点。
如果负载了就进行扩容然后重新计算hash值,然后根据新的hash值获得桶的索引,再次插入。如果键值不为空则根据键值算出新的hash,再根据hash算出新索引,计算新索引方法如下:
/**
* Returns index for hash code h.
*/
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);
}
这也是为什么必须要求hash表的长度是2的幂次方。再减一之后,除了最高位,其余位都是1,在和hash相与,得出结果。
我们可以看到如果容量是2的次方 , 那么length - 1得到的二进制的除了补位外都是1,根据&运算符的规则 , 0&0=0; 0&1=0; 1&1=1;那么也就意味着不论h的值是什么 , 只要length - 1的二进制码是这样的规律的 , 那么就 可以保证hash的值只和length - 1的同位参与了运算 .
例如二进制码A(10101011)&B(00001111)的结果就是C(00001011) , C的结果只会受到b二进制码后四位的影响,因为b的补位都是0 , 也就是说h & (length - 1)得到的索引不会大于length,也就不会越界。
如果键值不为空,那么就直接计算hash,得出索引进行循环。for循环遍历的是上面计算出来的桶索引代表的那个链表的所有节点。然后再判断这个链表里面有没有 和要插入的节点hash值相同并且equals或者==结果也相同的节点,如共有,就覆盖,并且返回旧值。否则就插入节点。
在这里浅放一下hash的方法:(手撸hash计算hash值可以以此为鉴)
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);
}
get()详解
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
键空,走getForNullKey()
private V getForNullKey() {
if (size == 0) {
return null;
}
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
这个和刚才看的put方法一致,都在再桶索引为0的地方存取,不用多说。
不空,进
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
首先根据键值计算出hash,然后根据hash计算出索引找到桶,遍历链表的每个节点,当遇到和目标hash相同并且key相同或者equals的节点,就返回。
resize()详解
这是一个扩容方法
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
新容量= 旧容量 * 2
新负载= 新容量*扩容因子
建立了新容器,要把旧容器的转移过去。transfer方法
/**
* Transfers all entries from current table to newTable.
*/
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;
}
}
}
元素迁移的过程中在多线程情境下有可能会触发死循环(无限进行链表反转)。
出现环形链表的原因大概是这样的:线程1准备处理节点,线程二把HashMap扩容成功,链表已经逆向排序,那么线程1在处理节点时就可能出现环形链表。