HashMap集合的简介
Map集合用语保存具有映射关系的数据,保存着两组值,一组用于保存key,一组用于保存Value,key和value保存的值可以是任何引用类型。key保存的值是不能重复的,value可以重复,key和value的值都可以为null,但是只允许最多一条记录key的值为null,value的值允许多条。HashMap是基于哈希表的,哈希表是由数组加链表共同构成的一个数据结构。内部是一个数组,存储的是一个Node<key,vlaue>的对象,Ndoe对象是基于链表实现的。但是在JDK1.8版本对HashMap进行了优化,当链表的长度过长时(默认为8)就会将链表专为红黑树结构。
HashMap源码分析
HashMap实现了Map、Serializable、Cloneable接口,继承了AbstractMap
成员变量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4//用来表示默认容量,相当于2*2*2*2=16
static final int MAXIMUM_CAPACITY = 1 << 30 //最大容量2的30次方
static final float DEFAULT_LOAD_FACTOR = 0.75f//默认加载因子,当哈希桶数组table中的元素大于容量*加载因子,会用resize方法扩容
static final int TREEIFY_THRESHOLD = 8//桶中的数据的节点数大于8时就转换为红黑树
static final int UNTREEIFY_THRESHOLD = 6//桶中的节点数小于6时转换为链表
static final int MIN_TREEIFY_CAPACITY = 64//当需要将解决hash冲突的链表变为红黑树时,需要判断下此时数组容量,若容量太小(小于
MIN_TREEIFY_CAPACITY)则不转为红黑树,而是用resize方法进行数组的扩容
transient Node<K,V>[] table//存储元素的数组,总是2的幂次倍
transient Set<Map.Entry<K,V>> entrySet//存放具体元素的集合
transient int size//HashMap的元素个数
transient int modCount//HashMap修改的次数,用于fail-fast机制
int threshold//阀值,threshiod=table*loadFactor,若size超过这个数就会扩容,扩容后容量是原容量的2倍
final float loadFactor//加载因子
内部类
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;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {//重写了Object的hasCode方法
return Objects.hashCode(key) ^ Objects.hashCode(value);//将key和value的hashCode按位异或。两个相等为0,不等为1
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {//重写equals方法
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;
}
}
构造方法
public HashMap(int initialCapacity, float loadFactor) {//指定初始容量和加载因子
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)//HashMap最大容量为2的30次方
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);//tableSizeFor方法返回的值是最接近initialCapacity的2次幂,注意此处只是给阀值赋值了。HashMap的容量并没有定义大小,依旧是空
}
public HashMap(int initialCapacity) {//指定初始容量
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(Map<? extends K, ? extends V> m) {//利用Map集合创建HashMap
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // 若元HashMap是空
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);//将Map里的元素添加到HashMap集合里
}
}
}
tableSiazeFor()方法:获取大于或等于cap的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;
}
这里必须要解释一下,为什么HashMap的容量一定要是2的次幂,因为当容量是2的次幂的时候,做hash算法获取元素下标位置能更加均匀,假设有两个HashMap容量(length)为16和15,现在有三个元素其key值的hash(h)为5、6、7,现在要通过取模运算(h&length-1)来算出key的所在位置。
上图会发现当容量为15时length-1为14,出现了hash碰撞,我们再夺取几个元素,结果会更直观。
从上图可以看出,当length为15时,有一半的位置发生了碰撞而且都是在偶数位置上。那是因为当length为级数时,length-1就为偶数,偶数的二进制最后一为肯定为0,所以不管hash值为多少算下来的位置肯定为偶数。
核心方法
在HashMap中无论是进行添加、删除、查找等操作都需要先利用key的hashCode()方法得到其hashCode,再通过hash算法确定该key所在位置。当两个key定位到相同的位置是就会发生hash碰撞。hash碰撞越少,HashMap的效率就会越高。
如果hash桶的数组很大,比较差的hash算法也会使元素比较分散。如果hash桶的数组很小,即使比较好的hash算法也会发生很多hash碰撞。所以要提高HashMap的效率需要两点:合适的扩容时机、好的hash算法。扩容时机和loadFactor加载因子有关,默认的loadFactor是0.75,建议不要修改。除非是特殊的要求,比如说空间很大,时间效率很高,可以减少loadFactor的值。反之亦然。
static final int hash(Object key) { //jdk1.8 & jdk1.7
int h;
// h = key.hashCode() 为第一步 取hashCode值
// h ^ (h >>> 16) 为第二步 高位参与运算
return(key == null) ? 0: (h = key.hashCode()) ^ (h >>> 16);
}
static int indexFor(inth,intlength) { //jdk1.7的源码,jdk1.8没有这个方法,但是实现原理一样的
returnh & (length-1); //第三步 取模运算,&按位与相当于取模运算,位运算速度更快
}
hash算法本质分3步:获取hashCode、高位参与运算、去模运算。
resize()扩容
/**
* 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;//定义临时Node数组型变量,作为hash table
//读取hash table的长度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;//读取扩容门限
int newCap, newThr = 0;//初始化新的table长度和门限值
if (oldCap > 0) {
//执行到这里,说明table已经初始化
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
}
else if (oldThr > 0) // initial capacity was placed in threshold
//用构造器初始化了门限值,将门限值直接赋给新table容量
newCap = oldThr;
else {
// zero initial threshold signifies using defaults
//老的table容量和门限值都为0,初始化新容量,新门限值,在调用hashmap()方式构造容器时,就采用这种方式初始化
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;//更新新门限值为threshold
@SuppressWarnings({"rawtypes","unchecked"})
//初始化新的table数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//当原来的table不为null时,需要将table[i]中的节点迁移
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//取出链表中第一个节点保存,若不为null,继续下面操作
if ((e = oldTab[j]) != null) {
oldTab[j] = null;//主动释放
if (e.next == null)
//链表中只有一个节点,没有后续节点,则直接重新计算在新table中的index,并将此节点存储到新table对应的index位置处
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
//若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 {
//下面这段暂时没有太明白,通过e.hash & oldCap将链表分为两队,参考知乎上的一段解释
/**
* 把链表上的键值对按hash值分成lo和hi两串,lo串的新索引位置与原先相同[原先位
* j],hi串的新索引位置为[原先位置j+oldCap];
* 链表的键值对加入lo还是hi串取决于 判断条件if ((e.hash & oldCap) == 0),因为* capacity是2的幂,所以oldCap为10...0的二进制形式,若判断条件为真,意味着
* oldCap为1的那位对应的hash位为0,对新索引的计算没有影响(新索引
* =hash&(newCap-*1),newCap=oldCap<<2);若判断条件为假,则 oldCap为1的那位* 对应的hash位为1,
* 即新索引=hash&( newCap-1 )= hash&( (oldCap<<2) - 1),相当于多了10...0,
* 即 oldCap
* 例子:
* 旧容量=16,二进制10000;新容量=32,二进制100000
* 旧索引的计算:
* hash = xxxx xxxx xxxy xxxx
* 旧容量-1 1111
* &运算 xxxx
* 新索引的计算:
* hash = xxxx xxxx xxxy xxxx
* 新容量-1 1 1111
* &运算 y xxxx
* 新索引 = 旧索引 + y0000,若判断条件为真,则y=0(lo串索引不变),否则y=1(hi串
* 索引=旧索引+旧容量10000)
*/
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;
}
put()添加元素
1 //指定节点 key,value,向 hashMap 中插入节点
2 public V put(K key, V value) {
3 //注意待插入节点 hash 值的计算,调用了 hash(key) 函数
4 //实际调用 putVal()进行节点的插入
5 return putVal(hash(key), key, value, false, true);
6 }
7 static final int hash(Object key) {
8 int h;
9 /*key 的 hash 值的计算是通过hashCode()的高16位异或低16位实现的:(h = k.hashCode()) ^ (h >>> 16),主要是从速度、功效、质量来考虑的,这么做可以在数组table的length比较小的时候,也能保证考虑到高低Bit都参与到Hash的计算中,同时不会有太大的开销*/
10 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
11 }
12
13 public void putAll(Map<? extends K, ? extends V> m) {
14 putMapEntries(m, true);
15 }
16
17 /*把Map<? extends K, ? extends V> m 中的元素插入到 hashMap 中,若 evict 为 false,代表是在创建 hashMap 时调用了这个函数,例如利用上述构造函数3创建 hashMap;若 evict 为true,代表是在创建 hashMap 后才调用这个函数,例如上述的 putAll 函数。*/
18
19 final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
20 int s = m.size();
21 if (s > 0) {
22 /*如果是在创建 hashMap 时调用的这个函数则 table 一定为空*/
23 if (table == null) {
24 //根据待插入的map 的 size 计算要创建的 hashMap 的容量。
25 float ft = ((float)s / loadFactor) + 1.0F;
26 int t = ((ft < (float)MAXIMUM_CAPACITY) ?
27 (int)ft : MAXIMUM_CAPACITY);
28 //把要创建的 hashMap 的容量存在 threshold 中
29 if (t > threshold)
30 threshold = tableSizeFor(t);
31 }
32 //判断待插入的 map 的 size,若 size 大于 threshold,则先进行 resize()
33 else if (s > threshold)
34 resize();
35 for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
36 K key = e.getKey();
37 V value = e.getValue();
38 //实际也是调用 putVal 函数进行元素的插入
39 putVal(hash(key), key, value, false, evict);
40 }
41 }
42 }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//先将table赋给tab,判断table是否为null或大小为0,若为真,就调用resize()初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//通过i = (n - 1) & hash得到table中的index值,若为null,则直接添加一个newNode
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//执行到这里,说明发生碰撞,即tab[i]不为空,需要组成单链表或红黑树
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//此时p指的是table[i]中存储的那个Node,如果待插入的节点中hash值和key值在p中已经存在,则将p赋给e
e = p;
//如果table数组中node类的hash、key的值与将要插入的Node的hash、key不吻合,就需要在这个node节点链表或者树节点中查找。
else if (p instanceof TreeNode)
//当p属于红黑树结构时,则按照红黑树方式插入
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//到这里说明碰撞的节点以单链表形式存储,for循环用来使单链表依次向后查找
for (int binCount = 0; ; ++binCount) {
//将p的下一个节点赋给e,如果为null,创建一个新节点赋给p的下一个节点
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果冲突节点达到8个,调用treeifyBin(tab, hash),这个treeifyBin首先回去判断当前hash表的长度,如果不足64的话,实际上就只进行resize,扩容table,如果已经达到64,那么才会将冲突项存储结构改为红黑树。
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果有相同的hash和key,则退出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;//将p调整为下一个节点
}
}
//若e不为null,表示已经存在与待插入节点hash、key相同的节点,hashmap后插入的key值对应的value会覆盖以前相同key值对应的value值,就是下面这块代码实现的
if (e != null) { // existing mapping for key
V oldValue = e.value;
//判断是否修改已插入节点的value
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;//插入新节点后,hashmap的结构调整次数+1
if (++size > threshold)
resize();//HashMap中节点数+1,如果大于threshold,那么要进行一次扩容
afterNodeInsertion(evict);
return null;
}
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;
// table已经初始化,长度大于0,且根据hash寻找table中的项也不为空
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;
}
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
//外层循环搜索数组
for (int i = 0; i < tab.length; ++i) {
//内层循环搜索链表
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
remove方法
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* 用于实现 remove()方法和其他相关的方法
*
* @param hash 键的hash值
* @param key 键
* @param value the value to match if matchValue, else ignored
* @param matchValue if true only remove if value is equal
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
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;
//table数组非空,键的hash值所指向的数组中的元素非空
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v; //node指向最终的结果结点,e为链表中的遍历指针
if (p.hash == hash && //检查第一个节点
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
//如果第一个节点不匹配
else if ((e = p.next) != null) {
if (p instanceof TreeNode) //树
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;//保存上个节点
} while ((e = e.next) != null);
}
}
//判断是否存在,如果matchValue为true,需要比较值是否相等
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode) //树
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p) //匹配第一个节点
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}