HashMap是一个基于键值对存储的数据结构,JDK 1.8中对HashMap的底层实现做出了一些优化,主要是引进了红黑树这一数据结构。
HashMap结构
HashMap是由数组+链表+红黑树组成,桶中可能是链表,也可能是红黑树,当链表的长度>=7,就尝试把链表转化为红黑树,引入红黑树主要是为了降低遍历层次,加快访问效率。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V 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;
}
每个节点都是一个Node,Node由hash,key,value,next组成,hash由key计算得出,next是指向下一个节点的指针。Node又实现了Map.Entry,本质上还是以Entry为基础进行操作。
HashMap属性
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认初始容量=16
// 最大容量 必须是2的整数次幂
static final int MAXIMUM_CAPACITY = 1 << 30;
// 加载因子 越接近1,存储的数据越多, 当HashMap中实际存储的元素个数 > 初始容量*加载因子,可能会发生扩容操作.
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 当链表的长度超过8的时候,就考虑把链表进行树化
static final int TREEIFY_THRESHOLD = 8;
// 当桶中的节点<6,树转化为链表
static final int UNTREEIFY_THRESHOLD = 6;
// 链表转化为红黑树时,table的容量最小值
static final int MIN_TREEIFY_CAPACITY = 64;
HashMap构造方法
// 自定义初始容量大小和负载因子,当容量<0,直接抛出异常,当容量>最大容量,把最大容量作为初始容量,当负载因子<=0 或者不是数字时,
// 直接抛出异常
// 初始化负载因子和扩容阈值(调用tablesizefor方法,找到>=初始容量的最小的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);
}
// 可以传入一个初始容量大小,使用默认的负载因子0.75f
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
// 默认无参的构造方法,使用默认的负载因子0.75f
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
// 初始化负载因子,将m中的所有元素添加到HahaMap中
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
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) {
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;
}
put存储元素时调用了putval方法,可以看到,这个方法中有5个参数,第1个参数是获取key的hash值,第4个参数是false,代表在key一致的情乱下,可以替换原value,第5个参数是true,只有创建table的时候才是false,其他情况都是true。key通过hash方法计算出hashcode,当计算处的hashcode与Map的length-1做&操作后,就会得到0到length-1之间的一个索引,这个值分布的越均匀,HashMap的空间利用率越好。
① 若table为空或table的长度为0,进行扩容操作。
② 根据key计算的hash值和table的长度-1进行与操作,得到插入的数组索引,如果该索引处的节点为空,直接新建节点添加。
③ 如果该节点的hash与key要与添加的key一致,直接覆盖原value值。
④ 判断该节点如果为TreeNode,那就用key的hash与红黑树的根节点的hash进行比较,如果key的hash值小,那就遍历根节点的左子树,如果key的hash值大,就就遍历根节点的右子树,直到能插入合适的位置。
⑤ 遍历链表,若key已经存在,直接覆盖value值;若key不存在,直接新建节点追加在链尾,判断链表的长度是否>=7,如果超过7,尝试把链表转化为红黑树(如果table的长度<64,直接进行扩容操作,否则,遍历该链表,把Node节点封装成TreeNode节点,接着把TreeNode转化为红黑树结构,可以跟着源码理解)。
⑥ 插入节点后,判断实际存储的键值对是否大于扩容阈值,如果超时,那就要进行扩容操作。
其中有两个方法afterNodeAccess和afterNodeInsertion为空,这是让LinkedHahshMap去重写此方法调整插入顺序的,有点类似模板方法的设计模式,父类定义了通用功能,子类去重写父类的钩子方法,来完成自己的特定功能的实现,不得不佩服作者的这种思想的升华。
resize方法
上面多次提到了扩容操作,总结一下,当table为空,或链表转化为红黑树,table长度<64,或是存储的键值对数量超过扩容阈值,就要进行resize操作,初始化table也包含在resize方法中,resize是一个非常耗时的操作,需要重新计算节点在新table中的索引然后复制处理,所以我们在可预估HashMap个数的时候,尽量在构造函数预设元素的个数,有利于性能的提升,分析下resize源码。
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table; // 保存当前的table
int oldCap = (oldTab == null) ? 0 : oldTab.length; // 保存table的大小
int oldThr = threshold; // 保存当前的扩容阈值
int newCap, newThr = 0;
if (oldCap > 0) { // 当前table>0,如果当前table容量>=最大容量, 把扩容阈值改为Integer的最大值,返回当前table
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; // 新数组的阈值变成原数组阈值的两倍
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // 这是table为空的情况,使用默认的容量和默认的负载因子
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) { // 如果新数组的扩容阈值=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,以新的容量创建一个新的table
table = newTab; // 把新table赋值给table
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 { // 此时这是链表,就要遍历该链表
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do { // 用(节点的hash & 原数组长度) == 0 来把链表分割,分成两个不同的链表
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) { // 把高位为0链表放在和原数组相同的索引上
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) { // 把高位为1的链表放在原数组长度+原数组索引的位置处
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab; // 最后返回扩容后的新数组
}
此时看一下节点是红黑树的情况,还是跟进一下源码
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode<K,V> e = b, next; e != null; e = next) { // 遍历TreeNode
next = (TreeNode<K,V>)e.next; // 和上面类似,把红黑树进行分割,分别统计树节点的个数
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
if (loHead != null) { // 高位为0的链表,若树节点的个数<=6,就把红黑树转化为链表,把链表放到和原数组相同的位置
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) { // 高位为1的链表,若树节点的个数<=6,把红黑树转化为链表,把链表放到原数组长度+原索引位置上
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
get方法
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;
}
前提条件:table不为空 && table长度>0 && 要查找的key的hash和数组长度-1与操作得出的index上的节点不为空,如果第一个节点的hash值和key与当前key一致的话直接返回该节点如果当前节点是TreeNode,在红黑树中去查找和key相等的节点(从根节点用hash开始比较,该节点hash值大,查找左子树,否则,查找右子树,如果某节点key与要查找的key相同,直接返回该节点,没找到直接返回null);如果当前节点不是TreeNode,那就遍历链表,找到与key相同hash相同的节点返回,没找到返回null。
remove方法
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 && // table不为空 && table长度>0 && 用key的hash计算
(p = tab[index = (n - 1) & hash]) != null) { // 出的索引处的节点不为空
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash && // 如果第一个节点的hash值和key与要移除的key一致,把该节点赋给node节点
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode) // 如果第一个节点是TreeNode节点,调用getTreeNode方法找出要移除的节点赋给node
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else { // 遍历链表,没有找到要移除的节点直接返回null,否则,把该节点赋值node
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value || //如果node节点不为空&&node.value=value
(value != null && value.equals(v)))) {
if (node instanceof TreeNode) // node是TreeNode节点,调用removeTreeNode方法移除该节点
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p) // 如果该索引上第一个节点就是要被移除的节点,直接把node下一个节点变成第一个节点
tab[index] = node.next;
else // 要移除的节点在链表中间,那就把node的上一个节点和下一个节点进行连接
p.next = node.next;
++modCount;
--size; // 移除节点之后,把存储的键值对数量减一
afterNodeRemoval(node); // 这个方法是让LinkedHashMap进行重写,调整节点顺序
return node; // 返回被移除的节点
}
}
return null;
}
remove调用了removeNode方法,这个方法也有5个参数,第4个参数是false,代表当value相等的时候,不会移除该节点,第5个参数是true,代表移除这个节点时可以移动其他的节点。其中removeTreeNode方法比较复杂,删除时,涉及到被删除的节点为黑色或者红色,左旋,右旋,着色等操作,所以我们应对红黑树有比较好的理解,要想理解红黑树,可以结合TreeMap源码进行分析。
HashMap遍历
第一种方式使用keyset函数。
HashMap<String,String> map = new HashMap<>();
map.put("java", "hello world");
map.put("python", "hello world");
map.put("golang", "hello world");
map.put("c++", "hello world");
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
String value = map.get(name);
System.out.println(name+":"+value);
}
第二种方式使用entryset函数。
HashMap<String,String> map = new HashMap<>();
map.put("java", "hello world");
map.put("python", "hello world");
map.put("golang", "hello world");
map.put("c++", "hello world");
Set<Entry<String, String>> keySet = map.entrySet();
Iterator<Entry<String, String>> iterator = keySet.iterator();
while (iterator.hasNext()) {
Entry<String, String> entry = iterator.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}
使用entryset遍历比keyset要快,因为keyset遍历的时候先得到key,在根据key得到它的value值。我们平时还是尽量使用entryset。
HashMap是我们平时使用最广泛的类之一,重要性不言而喻。而且也是面试的热点之一。
说一下我面试时遇到的问题:
1. HashMap的大小为什么是2的幂?
参照知乎上的回答:如果length不为2的幂,比如15。那么length-1的2进制就会变成1110。在h为随机数的情况下,和1110做&操作。尾数永远为0。那么0001、1001、1101等尾数为1的位置就永远不可能被entry占用。这样会造成浪费,不随机等问题。
2. 解决Hash冲突的办法?
链地址法(HashMap) 开放地址法(ThreadLocal采用了线性探测法) 再哈希法 建立公共溢出区
LinkedHashMap是一个有序的Map,它继承了HashMap的所有特性,可以通过对比Java基础-LinkedHashMap源码分析来更好的理解HashMap。jdk 1.8 通过加入红黑树对HashMap进行优化,关于红黑树,可以结合TreeMap的实现来更好的理解红黑树特性。