HashMap简介

-
HashMap 是一个典型的的key-vlaue形式的哈希表,通过把key的hash值映射到数组的某一位置来访问记录,加快访问速度
-
按图所示,HashMap数组中有两种存储方式,一类是链表结点,一类是红黑树结点
-
采用链表是为了处理映射到数组同一位置的不同节点造成的哈希冲突
-
采用红黑树是为了避免链表过长,而违背了哈希表O(1)查找的速度
HashMap属性
-
Node:存放key-value的数据结构
-
Node<K,V>[]:哈希表
-
loadFactor:负载因子,可以在构造函数中传入,来调整哈希表真实容量
-
threshold:扩容阈值,由数组长度*负载因子计算得出,构造函数中的threshold作用后面会写
//table数组默认大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//table最大长度
static final int MAXIMUM_CAPACITY = 1 << 30;
//负载因子(默认,也可以通过构造函数设置)
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//树化阈值:链表长度达到8会树化
static final int TREEIFY_THRESHOLD = 8;
//链化阈值:树的结点达到6会链化
static final int UNTREEIFY_THRESHOLD = 6;
//树化阈值:树化时hash表元素须达到64;
static final int MIN_TREEIFY_CAPACITY = 64;
//key-vlaue结点
static class Node implements Map.Entry {
//hash值:用来确定结点放在数组的哪个位置
final int hash;
final K key;
V value;
//next结点
Node next;
Node(int hash, K key, V value, Node 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);
}
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;
}
}
//存储key-value结点的哈希表
transient Node[] table;
//当前表中key-value结点个数
transient int size;
//当前表结构修改次数:用于fail fast机制
transient int modCount;
//扩容阈值:触发扩容的条件
int threshold;
//负载因子:计算threshold
final float loadFactor;
HashMap构造函数
-
参数initialCapacity:会被计算后赋值给threshold,在初始化时被当作数组长度,会重新计算threshold
-
参数loadFactor:赋值给负载因子,用来计算扩容阈值
-
构造函数中并没有初始化Node数组,而是等到put操作时,在扩容中初始化
//构造函数
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;
//返回一个大于等于cap的第一个2的次方
this.threshold = tableSizeFor(initialCapacity);
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//默认负载因子:0.75
//默认table长度:16
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
//通过一个Map构造HashMap
public HashMap(Map m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
-
hash():通过key计算hash值,封装在Node中,采用取余运算确定数组位置,取余运算被优化成了与运算,因为数组长度永远都是2的次方,比如17 % 16 等于17 & (16 - 1) = 1
-
tableSizeFor():计算出一个2的次方的数,其实就是初始化数组的长度
//让key的hash值的高16位也参与运算,减小hash冲突
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//作用:返回一个大于等于cap的第一个2的次方
//最高位的1一直取或,把后面的值全变成1
//再+1变成2的次方
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;
}
一个小细节:当key为null时,hash值为0
解析get()
-
get()方法用来根据key在哈希表中查找,根据key的hash值 & 数组长度减一(本质是取余数)来确定key在数组的哪个位置
-
找到key对应的数组位置后,再根据当前位置是链表还是红黑树查找
//真正操作在getNode中
public V get(Object key) {
Node e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node getNode(int hash, Object key) {
//tab:当前哈希表引用 first:当前位值第一个结点 n:数组长度 e:临时结点 k:临时结点的hash值
Node[] tab; Node first, e; int n; K k;
//当前散列表不为空,且key对应的位置有结点
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//情况1:第一个结点key和要查找的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) {
//情况2:红黑树查找
if (first instanceof TreeNode)
return ((TreeNode)first).getTreeNode(hash, key);
//情况3:链表查找
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
解析put()
-
put()操作用来在哈希表中添加一个结点,根据结点的key的hash值确定数组的位置
-
找到key对应的数组位置后,再根据当前位置的情况添加结点
//真正put操作在putVal中
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//onlyIfAbsent为false:表示当出现key相同时,put操作是替换旧的value
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
//tab:当前哈希表的引用 p:当前哈希表的元素 n:当前哈希表的长度 i:key的hash值计算出的哈希表的索引位置
Node[] tab; Node p; int n, i;
//延迟初始化,第一次putVal会初始化哈希表
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//情况1:对应的位置为null
if ((p = tab[i = (n - 1) & hash]) == null)
//直接插入
tab[i] = newNode(hash, key, value, null);
else {
//e:临时元素 k:临时元素的key
Node e; K k;
//情况2:对应的位置的key值和插入的key相等,表示后续需要赋值覆盖
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//情况3:对应的位置是红黑树
else if (p instanceof TreeNode)
e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
//情况4:对应的位置是链表
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;
}
}
//赋值覆盖操作
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()
-
当第一次put()操作时,会触发扩容操作初始化Node数组,构造函数中threshold会成为数组的长度,然后计算真正的扩容阈值赋值给threshold
-
当put()操作结束时,如果结点数量大于扩容阈值也会触发扩容操作
//扩容
final Node[] resize() {
//扩容前的哈希表
Node[] oldTab = table;
//扩容前的数组长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//扩容前的扩容阈值
int oldThr = threshold;
//新的扩容大小,新的扩容阈值
int newCap, newThr = 0;
//如果散列表已经初始化过了
if (oldCap > 0) {
//扩容之前数组已经达到最大
//不扩容,设置扩容阈值为int最大值
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
}
//oldCap = 0:说明哈希表未初始化
//情况1:通过new HashMap(initCap,loadFactor)
//情况2:new HashMap(initCap)
else if (oldThr > 0) // initial capacity was placed in threshold
//新容量为旧阈值,这个旧阈值时构造函数里计算出来的
newCap = oldThr;
//new Hashmap()
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[] newTab = (Node[])new Node[newCap];
table = newTab;
//旧数组已经初始化过
if (oldTab != null) {
、
for (int j = 0; j < oldCap; ++j) {
//当前node结点
Node e;
//当前桶位有数据
if ((e = oldTab[j]) != null) {
//方便GC回收
oldTab[j] = null;
//情况1:当前桶位只有一个元素
if (e.next == null)
//直接放入新数组
newTab[e.hash & (newCap - 1)] = e;
//情况2:当前桶位是红黑树
else if (e instanceof TreeNode)
((TreeNode)e).split(this, newTab, j, oldCap);
//情况3:当前桶位是链表
else { // preserve order
//拆成2链表
//第一个链表:存放在新数组中的位置和旧数组位置一样
Node loHead = null, loTail = null;
//第二链表:存放在新数组的位置为旧数组位置+旧数组的长度
Node hiHead = null, hiTail = null;
Node next;
//拆分链表
do {
next = e.next;
//高位为0
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
//高位为1
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;
}
解析remove()
-
remove()方法用来移除某个结点,根据结点的key的hash值确定数组的位置
-
找到key对应的数组位置后,再根据当前位置是链表还是红黑树查找并移除
//真正remove操作在removeNode中
public V remove(Object key) {
Node e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) {
//tab:当前哈希表 p:当前Node结点 n:数组长度 index:key对应的哈希表索引
Node[] tab; Node p; int n, index;
//哈希表不为空且key对应的位置有元素
if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
//node:查找的结果 e:临时结点 k:临时结点的key v:临时结点的value
Node node = null, e; K k; V v;
//情况1:查找的第一个元素就是要删除的元素
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
//情况2:红黑树
if (p instanceof TreeNode)
node = ((TreeNode)p).getTreeNode(hash, key);
else {
//情况3:链表
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//查到了node
if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) {
//情况1:红黑树(上面的情况2)
if (node instanceof TreeNode)
((TreeNode)node).removeTreeNode(this, tab, movable);
//情况2:链表头(上面的情况1)
else if (node == p)
//将该结点的下一个元素放到数组中
tab[index] = node.next;
//情况3:链表(上面情况3)
else
//通过上面情况3,p为node前一个元素
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}