HashMap是Java、Android面试中高频面试点,因为它涉及多种算法,且Java7和Java8中有不小的区别.本文,将学习HashMap的相关源码.
一.准备
1. hash碰撞
如果两个输入串的hash函数的值一样,则称这两个串是一个碰撞(Collision)。
计算得到的Hash值相同,需要放到同一个bucket(桶)中。
Hashmap里面的bucket出现了单链表的形式,散列表要解决的一个问题就是散列值的冲突问题,通常是两种方法:链表法和开放地址法。
链表法就是将相同hash值的对象组织成一个链表放在hash值对应的槽位;
开放地址法是通过一个探测算法,当某个槽位已经被占据的情况下继续查找下一个可以使用的槽位。
HashMap采用的链表法的方式,链表是单向链表。
2. HashMap的核心流程
3. 数组元素 & 链表节点的 实现类
HashMap
中的数组元素 & 链表节点 采用 Node
类 实现
与
JDK 7
的对比(Entry
类),仅仅只是换了名字
该类的源码分析如下:
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
* / 基本哈希bin节点,用于大多数条目。 (请参阅下面的TreeNode子类,以及LinkedHashMap中的Entry子类。)* /
Node = HashMap的内部类,实现了Map.Entry接口,本质是 = 一个映射(键值对)
实现了getKey()、getValue()、equals(Object o)和hashCode()等方法
**/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //哈希值. HashMap根据该值确定记录的位置
final K key; //key值
V value; //value值
Node<K,V> next; //链表下一个节点
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; }
//每一个节点的hash值,是将key的hashCode 和 value的hashCode 亦或(^)得到的。
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
//设置新的value 同时返回旧value
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
/**
作用:判断2个Entry是否相等,必须key和value都相等,才返回true
**/
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值,是将key的hashCode 和 value的hashCode 亦或(^)得到的。
4.红黑树节点的实现类
HashMap
中的红黑树节点 采用 TreeNode
类 实现
代码如下:
static final class TreeNode<K,V> extends LinkedHashMap.LinkedHashMapEntry<K,V> {
TreeNode<K,V> parent; // red-black tree links(红黑树链接) //父节点
TreeNode<K,V> left; //左边子树
TreeNode<K,V> right; //右边子树
TreeNode<K,V> prev; // needed to unlink next upon deletion(删除后需要取消链接) //删除辅助节点
boolean red; //颜色
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
/**
* Returns root of tree containing this node.
* (返回当前节点的根节点)
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
5. HashMap中的重要参数(变量)
- HaspMap的主要参数和JDK7一致,即 容量、加载因子、扩容阀值.
- HaspMap在JDK8中,相比JDK7,在数据结构中 增加了 红黑树
/**
主要参数(容量、加载因子、扩容阀值)与JDK7 一致,无论是要求、范围,均相同
**/
1.容量(capacity).必须是2的幂 以及 ≤最大容量(2的30次方)
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 (默认容量16)
static final int MAXIMUM_CAPACITY = 1 << 30; (最大容量.如果传入的值超过这个值,采用2的30次方赋值)
2.加载因子(load factor)
static final float DEFAULT_LOAD_FACTOR = 0.75f; //默认加载因子=0.75
final float loadFactor; //实际加载因子
3.扩容阈值(threshold) :当哈希表的大小(哈希表内元素数量) ≥ 扩容阈值时,就会扩容(resize())哈希表(即扩充HashMap的容量)
//a. 扩容 = 对哈希表进行resize操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数
//b.扩容阈值 = 容量 x 加载因子 ( 哈希桶.length * loadFactor )
int threshold;
4.其他
//哈希桶,存储数据的Node类型 数组,长度是2的N次方,或者初始化时为0;数组的每个元素 = 1个单链表
transient Node<K,V>[] table;
//HashMap的大小,即 HashMap中存储的键值对的数量
transient int size;
5.与红黑树相关的
//a.桶的树化阈值:即 链表转成红黑树的阈值,在存储数据时,当链表长度 > 该值时,则将链表转换成红黑树
static final int TREEIFY_THRESHOLD = 8;
//b.桶的链表还原阈值:即 红黑树转为链表的阈值,当在扩容(resize())时(此时HashMap的数据存储位置会重新计算),在重新计算存储位置后,当原有的红黑树内数量 < 6时,则将 红黑树转换成链表
static final int UNTREEIFY_THRESHOLD = 6;
// c.最小树形化容量阈值:即 当哈希表中的容量 > 该值时,才允许树形化链表 (即 将链表 转换成红黑树)
// 否则,若桶内元素太多时,则直接扩容,而不是树形化
// 为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLD
static final int MIN_TREEIFY_CAPACITY = 64;
二. 流程
1. 步骤一:构造函数
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
*使用指定的初始*容量和负载因子构造一个空的HashMap。
*@param initialCapacity初始容量
*@param loadFactor负载系数
@如果初始容量为负*或负载系数为非正数,则抛出IllegalArgumentException
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
//同时指定初始化容量 以及 加载因子, 用的很少,一般不会修改loadFactor
public HashMap(int initialCapacity, float loadFactor) {
//边界处理
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//初始容量最大不能超过2的30次方
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//显然加载因子不能为负数
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
//设置阈值为 》=初始化容量的 2的n次方的值
this.threshold = tableSizeFor(initialCapacity);
}
//新建一个哈希表,同时将另一个map m 里的所有元素加入表中
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* 构造一个空的HashMap ,它具有指定的初始容量和默认的负载系数(0.75)。
* @param initialCapacity 初始容量。
* @如果初始容量为负,则抛出IllegalArgumentException。
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
//指定初始化容量的构造函数
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
* 使用默认的初始容量(16)和默认的加载因子(0.75)构造一个空的的HashMap
*/
public HashMap() {
//默认构造函数,赋值加载因子为默认的0.75f
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
2.向HashMap添加数据(成对 放入 键 - 值对)
在该步骤中,与
JDK 7
的差别较大:
①计算桶的位置,根据key的hashcode求出hash值,位置index = hash%length。
②判断是否达到扩容条件,threshold=DEFAULT_INITIAL_CAPACITY * loadFactor(16*0.75=12)大于这个阀门值就需要扩容,否则下一步。
③判断桶位置是否为空,如果为空直接在数据插入数据。如果不为空,下一步。
④判断是链表还是红黑树,链表是否到达转化红黑树,当前链表节点数<=8,插入节点;如果是红黑树插入节点,否则下一步。
⑤链表转化成红黑树,插入节点。
⑥插入节点后计算当前size是否需要扩容,如果大于阀门值需要扩容resize。
/**
* Implements Map.put and related methods (实现Map.put和相关方法)
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value (如果为true,请不要更改现有值)
* @param evict if false, the table is in creation mode. (如果为false,则表处于创建模式。)
* @return previous value, or null if none (如果none,则返回之前的值或null)
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 1.若哈希表的tab为空,则通过resize()创建
// 所以初始化哈希表的时机=第一次调用put函数时,即调用resize()初始化创建
//关于resize()将在后面进行专门分析
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//插入时,判断是否有冲突. if 部分是没有冲突,else部分代表有冲突
// 若不存在冲突(即当前table[i] == null),则直接在该数组位置新建节点,插入完毕
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
/*表示有冲突(即当前插入的位置已经存在节点),开始处理冲突*/
//判断步骤如下: a.当前位置的key是否与需插入的key相同 b.判断需插入的数据结构是否为红黑树 or 链表
Node<K,V> e; K k;
// a. table[i]的元素的key是否与 需插入的key一样,若相同则 直接用新value 覆盖 旧value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//b. 继续判断:需插入的数据结构是否为红黑树 or 链表
//若是红黑树,则直接树中插入,或更新键值对
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//若是链表,则在链表中插入或更新键值对
// i:遍历table[i],判断key是否存在:采用equals(),对比当前遍历节点的key与需插入数据的key;若已存在,则直接用新value 覆盖 旧value
//ii:遍历完之后,仍未发现上述情况,则直接在链表尾部插入数据
//新增节点后(注意是之后),需判断链表长度是否>8(8 = 桶的树化阈值):若是,则把链表转换为红黑树
for (int binCount = 0; ; ++binCount) {
//对于ii:若数组的下一个位置表示已到标尾还没找到key值相同节点,则新增节点=插入节点.
//注意:此处是从链表尾插入,与JDK7不同(JDK7是从链表头插入,即永远都是添加到数组的位置,原来数组位置的数据则往后移)
/*指针为空就挂在后面*/
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果冲突的节点数已经达到8个,看是否需要改变冲突节点的存储结构,
//treeifyBin首先判断当前hashMap的长度,如果不足64,只进行resize,扩容table,如果达到64,那么将冲突的存储结构为红黑树.
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
/*如果有相同的key值就结束遍历*/
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//对i 情况的后续操作.发现e值存在,直接用旧value替代新value,& 返回旧value
if (e != null) { // existing mapping for key 就是key的Value存在
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue; //返回存在的Value值
}
}
++modCount;
//插入成功后,判断实际存在的键值对数量size>最大容量threshold
//如果大于,则需要扩容 (扩容后面单独分析)
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
以上是JDK 8的HashMap的put调用关键方法源码。
2. get获取过程
①计算桶的位置,根据key的hashcode求出hash值,位置index = hash%length。
②无论是数值,链表还是红黑树,for循环判断hash值冲突就比对key是否相等,相等就返回对应的value。
/**
* Implements Map.get and related methods (实现Map.get和相关方法)
*
* @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;
//计算存放在数组table中的位置
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//a.先在数组中查找.若存在,则直接返回
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//b. 若数组中存在,则在红黑树中查找
if ((e = first.next) != null) {
if (first instanceof TreeNode)
//在树中get
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//c.若红黑树中也没有,则通过遍历,在链表中查找
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
以上是JDK 8的HashMap的get调用关键方法源码。
3. 扩容
该函数有2种使用情况:1.初始化哈希表 2.当前数组容量过小,需扩容
/**
* 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.
*
* (**初始化或加倍表大小**。如果为空,则根据字段阈值中保持的初始容量目标分配*。 否则,因为我们使用的是2的幂,所以每个bin中的元素必须保持相同的索引,或者在新表中以2的偏移量移动*。)
*
* @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;
//针对情况2,若扩容前的容量已经是最大值了,则不再扩容
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 针对情况2:若无超过最大值,就扩充为原来的2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
/*把新表的门限设置为旧表门限的两倍,newThr=oldThr*2*/
newThr = oldThr << 1; // double threshold
}
// 针对情况1:初始化哈希表(采用指定 or 默认值)
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);
}
//计算新的resize上限
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
if (oldTab != null) { //原表不是空,把每个bucket都移动到新的buckets中
/*遍历原来的旧表*/
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null) //说明这个node没有链表,直接放在新表的e.hash & (newCap - 1)位置
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode) /*如果e后边有链表,到这里表示e后面带着个单链表,需要遍历单链表,将每个结点重新计算在新表的位置,并进行搬运 */
((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;
}
//原索引 + oldCap
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) { //lo队不为null,放在新表原位置.// 原索引放到bucket里
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) { //hi队不为null,放在新表j+oldCap位置
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
三.线程问题
HashMap 是线程不安全的.
如何线程安全的使用 HashMap?
- Hashtable
- ConcurrentHashMap
- Synchronized Map
//Hashtable
Map<String, String> hashtable = new Hashtable<>();
//synchronizedMap
Map<String, String> synchronizedHashMap = Collections.synchronizedMap(new HashMap<String, String>());
//ConcurrentHashMap
Map<String, String> concurrentHashMap = new ConcurrentHashMap<>();
推荐阅读: