HashMap是平时编码使用频繁的类,也是面试会经常问到的东西,源码有非常多的精妙的设计,通过阅读源码分析HashMap是非常有必要的,由于篇幅所限,在此只分析部分重要方法。
HashMap和HashTable非常的相似,除了它是不同步的(非线程安全)并且可以为空值(key ,value)。不过可以通过Collections.synchronizedMap方法使其同步。
下面先用图(来源)来描绘一下HashMap。
HashMap由数组+链表+红黑树构成。HashMap继承AbstractMap并实现Map,Cloneable,Serializable接口。要注意HashMap的实例有两个影响其性能的参数:初始容量和负载因子。
- 负载因子
/**
* 负载因子,负载因子是衡量哈希表在其容量自动増加之前
* 允许达到多满的指标。当哈希表中的条目数超过负载因子和当前容量的乘积时,重新合
* 希表(即重建内部数据结构)。
* 作为般规则,默认负載因子(0.75)在时间和空间成本之间提供了很好的权衡。较高的
* 值会减少空间开销,但会增加查找成本(反映在 Hashmapi类的大多数操作中,包括get
* 和put)。
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
- 初始容量
/**
* 初始容量,必须是2的幂,默认16 每次扩容为初始容量的2倍
* 送代集合视图需要的时间与 Hashmap实例的容量(桶的数量)加上它的大小(键
* 值映射的数量)成正比。因此,如果送代性能很重要,则不要将初始容量设置得太高
* (或负载因子太低),这一点非常重要。
* 设置初始容量时应考虑映射中的预期条目数及其负载因子,以尽量减少重新
* 哈希操作的次数。如果初始容量大于最大条目数除以负载因子,则不会重新哈希操作
* 如果要在一个 Hashmap实例中存储许多映射,则创建具有足够大容量的映射将允许更有
* 效地存储映射,而不是让它根据需要执行自动重新散列以。
*/
static final int DEFAULT_INITIAL_CAPACITY=16;
为什么要是2的幂?
:HashMap为提高get put效率,减少碰撞。取模算法hash%length ,hashmap将其优化成位运算hash&(length-1),但hash%length等于hash&(length-1)的前提是length是2的n次幂。
红黑树与链表转化的关键成员变量
/**
* 链表转为红黑树的临界值,必须大于2且最少为8
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 红黑树退化为链表的临界值
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 链表转红黑树的最小容量
*/
static final int MIN_TREEIFY_CAPACITY = 64;
当这个链表长度大于阈值8并且数组长度大于64则进行将链表变为红黑树。
将链表转换成红黑树前会判断,如果阈值大于8,但是数组长度小64,此时并不会将链表变为红黑树。而是选择进行数组扩容。
以上都是为了提升性能和效率,红黑树为维持平衡本身有一定开销
数组表:
/**
* 存储Node的数组表,长度大小始终为2的幂
*/
transient Node<K,V>[] table;
fail-fast 机制变量
/**
*修改次数,与fail-fast机制有关,在并发是,modCount 跟 expectedModCount 是否相等,如果不相等就表示已经有其他线程修改了 Map,将抛出ConcurrentModificationException
*/
transient int modCount;
其余的成员变量:
/**
* 默认最大容量
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* Node节点的数量
*/
transient int size;
/**阀值,触发 HashMap 扩容的值(capacity * load factor).*/
int threshold;
/**负载因子*/
final float loadFactor;
基本的Node节点
/**
*基本的Hash节点
*/
static class Node<K,V> implements Map.Entry<K,V>{
final int hash;
final K key;
V value;
Node<K,V> next;
// ...get set
@Override
public V setValue(V newValue) {
V oldValue = value;
value=newValue;
return oldValue;
}
@Override
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
@Override
public boolean equals(Object obj) {
//如果是同一个对象
if(obj==this){
return true;
}
//否则先判断类型,再比较键和值
if (obj instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)obj;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
初始化
这里可以注意到,初始化时并没有创建数组,而是在第一次写入时创建。
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;
this.threshold = tableSizeFor(initialCapacity);
}
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;
}
put操作
put key可以为空
对于key==null,放在0的位置
如下:jdk1.8
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);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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;
//如果要要放的位置有元素了
//如果要放的元素的key等于原有的元素的key
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 {
//还是list,按照list的方式放,循环查找
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;
}
}
// 新key和旧key相同,直接覆盖
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//帮助fail-fast的参数
++modCount;
//判断大小,扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
读取
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
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) {
//检查第一个的key
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);
//如果是list
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
扩容:扩容为原来的两倍
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
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) {
//判断初始大小,如果大于等于最大默认容量则把阀值变为Integer的最大值,暂时不扩容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//否则,扩容变为原来容量的两倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//旧容量<=0,阀值大于0
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;
if (oldTab != null) {
//for循环,对所有元素Hash
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 {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
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;
}