源码分析HashMap
1、Map结构的理解(以HashMap为例):
Map中的Key:无序的、不可重复的,使用Set存储所有的Key,Key所在的类要重写equals()和hashcode()方法。
Map中的Value:无序的、可重复的,使用Collection存储所有的Value,Value所在的类要重写equals()方法。
一个Key-Value键值对构成了一个Entry对象。
Map中的Entry:无序的、不可重复的,使用Set存储所有的Entry。
2、HashMap基本使用
@Test
public void test() throws Exception {
HashMap<String, Integer> map = new HashMap<>();
map.put("1", 1);
map.put("2", 2);
map.put("4", 3);
map.put("5", 3);
map.put("6", 3);
map.put("7", 3);
System.out.println(map);
}
运行结果:
{1=1, 2=2, 4=3, 5=3, 6=3, 7=3}
3、源码分析
先来熟悉一下几个常量和属性:
常量:
①、DEFAULT_INITIAL_CAPACITY:默认的初始化容量,为16
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
②、MAXIMUM_CAPACITY:HashMap最大的容量,为Integer.MAX_VALUE
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
③、DEFAULT_LOAD_FACTOR:默认的负载因子,为0.75f
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
④、TREEIFY_THRESHOLD:将链表转化为红黑树的链表长度
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
⑤、UNTREEIFY_THRESHOLD:将红黑树转为链表的子节点个数
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
⑥、MIN_TREEIFY_CAPACITY:将链表转为红黑树的最小数组长度(与TREEIFY_THRESHOLD配合使用)
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
属性:
①、table:结点数组,每个链表的头节点,存储所有结点
/**
* 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;
②、entrySet:存储Map中所有的键值对
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
③、threshold:阈值,即HashMap中结点数超过该值就进行扩容,计算方法为 capacity * load_factor
/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
在进入源码前,先来理解一下负载因子的作用:
用于表示哈希表中元素填满的程度。
冲突的机会越大,则查找的成本越高。反之,查找的成本越低,从而查找的时间越少。
所以,在默认情况下,当table中的结点个数达到了16 * 0.75 = 12 时HashMap就会进行扩容。
Ⅰ、查看HashMap的构造器:
//无参构造器
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//有参构造器1,传入初始容量
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//有参构造器2,传入初始容量和自定义负载因子
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);
}
Ⅱ、向HashMap中添加键值对
//插入键值对
public V put(K key, V value) {
//调用putVal方法添加Key-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;
//判断结点数组是否为空,若为空则对数组进行resize()操作
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的hash与原有的key相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//将原结点的指针赋给e
e = p;
//若该节点是红黑树中的结点
else if (p instanceof TreeNode)
//调用红黑树中添加结点的方法
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//否则遍历该链表的所有结点
for (int binCount = 0; ; ++binCount) {
//如果该结点的下一节点是null
if ((e = p.next) == null) {
//创建一个新的结点进行插入,使用尾插法
p.next = newNode(hash, key, value, null);
//判断当前链表长度是否超过转为红黑树的阈值
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//如果超过则转为红黑树
treeifyBin(tab, hash);
break;
}
//如果找到与预插入的key相同的key
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//如果HashMap中已经存在了相同的key
if (e != null) { // existing mapping for key
//将e的value赋给oldValue
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
//将新的value赋给e
e.value = value;
afterNodeAccess(e);
//返回旧值
return oldValue;
}
}
++modCount;
//如果map中的键值对个数超过了阈值,则进行扩容操作
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
Ⅲ、HashMap中的resize()方法:
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
//获得原本table的长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//获得阈值大小
int oldThr = threshold;
int newCap, newThr = 0;
//若旧容量大于0
if (oldCap > 0) {
//判断旧容量是否超过最大值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//若两倍的旧容量依旧小于最大容量,且旧容量大于默认容量16
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//将阈值扩大两倍
newThr = oldThr << 1; // double threshold
}
//若旧阈值大于0
else if (oldThr > 0) // initial capacity was placed in threshold
//将旧阈值赋给新容量
newCap = oldThr;
else { // zero initial threshold signifies using defaults
//修改容量为默认容量16
newCap = DEFAULT_INITIAL_CAPACITY;
//修改阈值为16 * 0.75 = 12
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//如果新阈值为0,则修改新阈值的大小
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;
//如果原有的table不为null,则将原table所有的结点迁移newTab
if (oldTab != null) {
//遍历原table所有的结点
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//若原table在该索引不为null
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//若该链表只有一个结点
if (e.next == null)
//直接将该结点放入新的table中
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 {
//得到e的next结点
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) {
//将尾部元素置为null
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}