HashMap的特点
- 从JDK1.8开始HashMap的存储结构变成了数组+链表+红黑树,单链表中元素个数超过指定阈值,会转化为红黑树结构存储(提高查询效率);
- 从1.7到1.8,在hash冲突的时候,链表的插入将头插法改为尾插法,防止在高并发的情绪出现循环链表;
- HashMap的默认数组大小为16,代表hash数组的长度;
- 默认的加载因子是0.75,代表存入元素大于数组大小*加载因子就进行扩容;
- HashMap是线程不安全的,方法都未使用synchronized关键字;
- 允许key和value值为null(默认hash算法的情况下,放在数据的0号位置);
静态变量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
元素插入
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (<