HashMap默认初始容量为16,默认加载因子为0.75.,HashMap数据存储在Node数组中。
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
HashMap的put(Key k, Value v)过程:
1. 通过key计算数组下标,计算公式:数组下标 = (n - 1) & hash
2. 不同key的hashcode可能相同,所以计算出来的数组下标也有可能相同,如果计算出的数组下标已经有元素存在则出现hash冲突。
(1)如果没有hash冲突,直接放入数据到对应下标的链表中。
(2)如果有hash冲突,调用key的equals方法对比两个key是不是equals,如果是eqauls则用新的value覆盖旧的value,如果不equals则加入到数组对应下标的链表中。
3. 如果链表长度超过阀值(TREEIFY_THRESHOLD == 8),就把链表转成红黑树。
4. 如果桶满了(容量 * 加载因子),就需要resize。
HashMap的V get(Object key)过程: