HashMap概述
工作原理:HashMap的底层数据结构是数组加链表。通过hash(链地址法解决hash冲突)的方法,使用get和put获取和存储对象。存储对象时,将K/V传给put方法,put方法调用hashCode计算hash从而得到在bucket中的位置,若此位置没有元素,则直接放置在此位置,若有元素,则放置在链表的开头。同时,HashMap也会根据当前bucket的占用情况自动调整容量。获取对象时,将K传给get,它调用hashCode计算hash从而得到bucket位置,并进一步调用equals方法确定键值对。
HashMap允许null 键值对,即键和值都能为null,非同步,不保证有序,也不保证顺序不随时间变化(resize操作会修改顺序),当key为null时,放置在第一个桶中,即hash值为0
HashMap字段解释
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //HashMap默认大小为16
static final int MAXIMUM_CAPACITY = 1 << 30;//最大存储容量2的20次方
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认的加载因子,会影响HashMap性能的一个数值,一般不需要修改
static final int TREEIFY_THRESHOLD = 8;//碰撞临界值,超过此值,会将链表修改为红黑树
transient Node<K,V>[] table;//保存元素的数组,长度为2的幂,根据情况进行大小的调整,为什么使用transient,为了防止使用Serializable接口中的序列化方法,因为table的大小可以调整,里面有可能会存在很多的null值。但是HashMap定义了自己的readObject和writeObject方法,使用自己定义的方法进行table的序列化,防止空间的浪费。
transient int modCount;//当修改HashMap的结构时,会改变modCount的值,用于iterator的fast-fail
int threshold;//下一个进行resize操作的值,一般等于(capacity * load factor)
方法说明
内部结构Node
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next; //Node中有此元素的hash值,键key,值value,下一个元素
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);//通过hashCode计算key和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;
}
}
hash方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//若key不为null,将key的hashCode值的高16位与低16位进行异或操作
}
tableSizeFor方法
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
给出大于cap且为2的幂的最近的值,如cap=5,则输出8
HashMap的初始化方式
- public HashMap(int initialCapacity, float loadFactor){}
- public HashMap(int initialCapacity){}
- public HashMap(){} 默认容量为16,load factor为0.75
- public HashMap(Map
get方法(获取元素)
- 根据给定的key值,使用hash方法计算对应的hash值
- 根据hash值利用公式(n-1)&hash得到在table中的位置,其中n为table的长度(即HashMap的容量)
- 如果table中第一个元素的hash值等于给定的hash值并且两者的键引用指向同一个地址或者两者的键值equal相等,则放回第一个元素
- 若3中的条件不满足,则在链表的下一个元素进行此条件的比较,因为java8中根据碰撞会有红黑树以及普通链表的区别,所以这里还要进行判断,是红黑树还是普通链表。直到链表的元素为null或者满足条件或者找不到。
- 返回找到的value值或者null
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key); //红黑树
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
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) {
//onlyIfAbsent为true,不改变HashMap中已经存在的value值
//evict为false,数组是刚开始进行构建的
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 (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;
}
扩容resize方法
jdk8中的resize方法能够保证HashMap中原来元素在链表中的顺序,而原来的方法是将链表的顺序颠倒了
resize方法具体细节可以参考链接-美团技术
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
// 超过最大值就不再扩充了,就只好随你碰撞去吧
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 没超过最大值,就扩充为原来的2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
} //运算符优先级 ‘<’>‘&&’>三目运算符
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 把每个bucket都移动到新的buckets中
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do { //jdk中优化后的方法,跟以前的resize方法是有区别的
next = e.next;
// 原索引
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
// 原索引+oldCap
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}