HashMap
HashMap是基于哈希表的 Map 接口的实现。HashMap 的实例有两个参数影响其性能:初始容量(16)和加载因子(0.75)。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 初始容量16
static final float DEFAULT_LOAD_FACTOR = 0.75f;//加载因子0.75
HashMap的特点:
- HashMap中允许存放null键、null值
- 线程不安全 –线程不同步
- 与HashTable大致相同
- Hashset是HashMap的实例 HashMap的底层是HashTable哈希表
- 在Java中 HashTable的父类是Dictionary
HashMap的底层结构主要是链表和数组,在jdk1.8之后增加了红黑树。如果链表长度超过阀值,就把链表转成红黑树,链表长度低于6,就把红黑树转回链表。
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16(初始容量默认16)
static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量为2^30
static final float DEFAULT_LOAD_FACTOR = 0.75f;//加载因子默认0.75
static final int TREEIFY_THRESHOLD = 8;//树化阀值
static final int UNTREEIFY_THRESHOLD = 6;//阀值
static final int MIN_TREEIFY_CAPACITY = 64;
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;//链表
...
}
...
transient Node<K,V>[] table;//数组
...
}
HashMap的put方法(源码)
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//i : key的hashcode运算后的值赋给i作为key在数组中的索引
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
未完待续…