源码版本:jdk1.8
接口继承
源码注释概要:
- 允许key和value的值为null
- 与Hashtable不同的地方,HashMap是unsynchronized,线程不安全,Hashtable不允许key和value为null,但是线程安全
- 迭代整个HashMap的时候,时间复杂度是和HashMap实例的容量呈正相关的,如果业务需要经常迭代整个HashMap,初始容量不要设置得过高(负载因子也不要设置得太低)
- 容量定义:HashMap的bucket数目
- 负载因子定义:在容量自动扩容之前,装物品的一个度量值,比如现在有10个bucket,现在负载因子定义为0.6,那么装满了6个bucket之后就不能再装了,就需要扩容之后才能继续装。
- 重建规则:键值映射数量> 负载因子*容量,HashMap的结构将被重建,容量变为2倍,结构被重建,意味着不同时间迭代同一个HashMap顺序可能会不同
- 负载因子默认值为0.75,平衡考虑了时间复杂度和空间复杂度。负载因子高,空间利用率高,但是会增加查询消耗,负载因子低则会导致空间浪费。
- Map m = Collections.synchronizedMap(new HashMap(…)) 这样使用,可以保证HashMap的原子性
10.迭代器的方法都采用了fail-fast(快速失败机制),只要在迭代的时候哈希表被修改,就会及时抛出ConcurrentModificationException异常,而避免以后出现不定期的,难以定位的错误。
底层使用数组、链表、红黑树实现。
HashMap采用链地址法来实现,将所有关键字为同义词的结点链接在同一个单链表中,也就是同一个bucket中。
- 可以结合三者的优点,数组便于随机存储,所以计算hash码所在的bucket最为合适
- 链表正好维护处于一个bucket的所有Node节点。链表便于修改,删除,时间复杂度为O(1),但是查询只能按链查找,时间复杂度为O(N)。
- 但是链表查找的时候时间复杂度为O(N),如果链表过长,时间消耗太多,所以,对应bucket的Node节点如果过多,就转为红黑树维护,这样查询,修改,删除都是O(logN)的时间复杂度
哈希存储结构
定义了一个Node<K,V> 的内部类,实现了Map.Entry<K,V>的接口,维护<K,V>键值对,普通链表节点使用Node维护,红黑树节点使用TreeNode
TreeNode 继承了LinkedHashMap.Entry<K,V>
get()
get(Object key)方法根据指定的key值返回对应的value,该方法调用了getNode(hash(key), key)得到相应的Node,然后返回对应Node.value。
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
算法思想是首先通过hash()函数得到对应bucket的下标,然后查找对应bucket的链表或者红黑树,通过key.equals(k)方法来判断是否是要找的那个键值对Node。
hash()
hashCode 为native方法,这里主要好奇的是为啥要这么异或。hashCode()方法返回的是int类型的数据,总共4字节,一共32位。
因为哈希表bucket数组的容量为2的幂次方,所以是仅在当前数组mask上的比特上变化的哈希值将会总是发生碰撞。
hashCode的高16位异或低16位得到哈希值,这样既减少了哈希碰撞,同时也不是很复杂,没有增加多少系统的开销。
为什么(hashcode >>> 16)
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
getNode()
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;
}
首先会检查第一个Node,如果不是,就判断这个Node上面是不是一棵树,是树就在树上查找,不然就依次的按链表顺序查找。
大致示意图如下所示。
我们还可以看到,源码中找对应的bucket是通过这个(n - 1) & hash实现的,这就是为什么哈希表的容量必须为2的幂次方的原因,可以使用位运算快速求出要查询的hash码所在的bucket 。如上所示,容量为8的哈希表,n-1=0111 ,与hash码相与,正好消掉高位,使得只能映射到0-7区间内,也等价于hash%8。但是一般位运算会比较快
put()
调用putVal()方法,这里第四个参数对应putVal()的onlyIfAbsent(),写死了,为false。
为true时,只有哈希表不存在这个key,才会put
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
putVal()
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;
//取所在的bucket,如果为null,则建立一个
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);
//这里设置的是一个阈值,表明链表的长度如果刚好达到TREEIFY_THRESHOLD常量,就调用treeifyBin()方法,将链表转为红黑树
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;
}
}
//如果找到了这个key已经存在,覆盖掉以前的键值对映射
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//快速失败机制的modCount
++modCount;
//先插入,再扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
这里有一个有意思的地方就是,链表转为红黑树的部分,大家试想,为什么不插入链表的时候,链表维护的数据数超过TREEIFY_THRESHOLD常量就直接转为红黑树呢?
这里非常类似懒加载,懒惰标记之类的思想。因为并不是每一个链表的数据我们都需要将他转化为红黑树,因为转化是需要时间消耗的,这个工作我们不一定要做。只有等别人查询到他的时候,我们才转化。就好像平时我们做工作,没必要把所有事都按照最终标准来,说不定我们弄的那个东西别人根本不会来查,这样我们的工作就没有意义。所以不要用勤奋要掩盖你战术上的懒惰就是这个意思。
当链表长度大于TREEIFY_THRESHOLD常量时,并且此时哈希buckets数组容量必须大于MIN_TREEIFY_CAPACITY才能将链表转为红黑树
remove(Object key)
其实感觉有时候源码为啥要封装成多个函数?
但是看的时候又会发现,你能够很清晰的明白这个函数是干嘛用的,所以把业务尽量拆成了单一职责的业务,是为了方便调试和理清业务逻辑吧。
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
removeNode()
参数
- hash: key的hash值
- key
- value
- matchValue 如果为真,只在值相等时移除
- movable 如果为false,则在移除时不要移动其他节点
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;
//找对对应的bucket
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
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);
}
}
//删除指定的node
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;
}
扩容操作resize()
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) { //哈希表平常扩容进入的分支,而下面的else分支对应的HashMap几个构造函数对应的情况
if (oldCap >= MAXIMUM_CAPACITY) {
//threshold设置到Integer的最大值,但是并不扩容,返回
threshold = Integer.MAX_VALUE;
return oldTab;
}
//数组大小*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // 阈值也乘2
}
else if (oldThr > 0) //对应的HashMap(int initialCapacity, float loadFactor)构造出来的hashMap,第一次put的时候进入
newCap = oldThr;
else { // 其他构造方法,第一次put的时候进入
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<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
//遍历原数组,将非空元素复制到新数组里面去
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) { //该bucket不为null
oldTab[j] = null; //原数据置为null,数据已经由e接手
if (e.next == null) //该bucket只有一个元素
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 {
next = e.next;
//判断这条元素链表是否需要更换bucket
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);
//不需要移动bucket,在新表的 原bucket位置 也就是j放入这个链表
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
//需要移动bucket,在新表的 原bucket+原表容量 位置放入这个链表
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
这里面链表复制那一段代码维护了两个链表,然后分别放在新表不同的bucket的里面
- 一类链表是需要移动bucket的元素
- 一类链表维护的是不需要移动bucket的元素
比如我们原来哈希表的bucket数目为8,那么编号就是0-7
现在我们老表里面的2号bucket下存放的有10,18,26等hash码的元素,那么分别移动到新表的哪些bucket里面呢?
10&8=8 需要移动到2+8(原来的容量大小)的bucket里面
18&8=0 不需要移动bucket
26&8=8 需要移动到2+8(原来的容量大小)的bucket里面
存放在老表的2号bucket里面的元素只可能是哈希码为8x+2(x为自然数),所以说具有16x+2(x为自然数)的哈希码元素就不用移动到其他的bucket里面。
我们只需要将元素的hash码与原来的容量大小相与即可知道是否该移动这个元素到新的bucket里面去。
自定义对象哈希
在HashMap的put()函数运行的代码中,我们会发现hashCode()和equals()方法是做判断对比Key所要用到的函数。
hashCode()是Native()方法。
HashMap的equals()是使用Object的equals()方法,如下面代码所示是直接用==比对的
public boolean equals(Object obj) {
return (this == obj);
}
所以不适用于对象,但是我们使用的Integer,String等包装类却可以,进入他们的源码可以看到都是重写了这两个方法的,所以我们自己定义的类也需要重写这两个方法。
public static int hashCode(int value) {
return value;
}
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
如果我们不重写这两个方法
使用如下代码测试
public class A{
static class People {
int age;
int sex;
String name;
public People(int age,int sex,String name){
this.age = age;
this.sex = sex;
this.name = name;
}
@Override
public String toString() {
return "People{" +
"age=" + age +
", sex=" + sex +
", name='" + name + '\'' +
'}';
}
}
public static void main(String[] args){
HashMap<People,Integer> hashMap = new HashMap<>();
hashMap.put(new People(1,0,"tom"),1);
hashMap.put(new People(1,0,"tom"),2);
hashMap.put(new People(2,1,"jim"),3);
for(People people:hashMap.keySet()){
System.out.print(people);
System.out.printf(":%d\n",hashMap.get(people));
}
System.out.println(new People(1,0,"tom").hashCode());
System.out.println(new People(1,0,"tom").hashCode());
System.out.println(new People(2,1,"jim").hashCode());
}
}
运行结果
可以看见HashMap存入多个具有同样值的Key,不然按照HashMap的规则应该将用新的Value覆盖老的Value,只会保留一个<Key,Value>映射,但是这里有两个。
对于hashCode(),我们可以看见具有相同值的两个People实例的哈希码是不一样的,这个hashCode()是Native方法。
对于equals(),调用Object.equals()方法
public boolean equals(Object obj) {
return (this == obj);
}
因为java是函数调用是传的实例的地址,同时因为我们new的多个对象实例地址不一样,这样就会出错。
在People类里面重写Object类的这两个方法即可
@Override
public int hashCode() {
final int prime = 13331;
long code = 1;
code = (prime * code + age)%Integer.MAX_VALUE;
code = (prime * code + sex)%Integer.MAX_VALUE;
code = (prime * code + name.hashCode())%Integer.MAX_VALUE;
return (int)code;
}
@Override
public boolean equals(Object obj) {
if (obj == null){
return false;
}
if (this == obj){
return true;
}
if (getClass() != obj.getClass()){
return false;
}
People contrast = (People) obj;
if (age != contrast.age){
return false;
}
if(sex != contrast.sex){
return false;
}
if(!name.equals(contrast.name)){
return false;
}
return true;
}}
文章内容来自对网络资料,书本的归纳整理和自己的实践,如果有理解错误或者不足的地方,还请不吝赐教。