众所周知,hashMap的使用率在开发中有着极高的位置,而且在面试中也是经典。下面让我们走进hashMap的世界。
**
一、HashMap的数据结构
**
当我们打开hashMap的源码时候,发现一堆堆的代码,看起来繁琐复杂晦涩难懂,对于初学者是个挑战,比如下面的源码片段
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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;
}
这个代码是在hashmap进行put时进行执行的,看起来没有头绪。下面就先基本的进行开始。
**
1.1、数组的数据结构。
**
数组是在内存中开辟一段连续的空间,并在此空间存放元素。
特点是:存放的元素类型固定,长度也是固定的,查询速度快,增删慢。
1.2、linkedList的数据结构
LinkedList采用的是链表进行存储。链表又分为单向链表,双向链表,有序链表。
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
从上述代码的片段中可以发现LinkedList是双向链表。
单向链表的数据结构图
双向链表的数据结构图
链表的特点:查询慢,增删快。
进行推测:既然数组与LinkedList都无法满足需求,那么将两者的优点进行结合起来是否满足需求呢?
**
1.3、推测hasMap的数据结构
**
先进行画图
如果如上图所示那该如何进行表示每个节点呢?而且我们知道HashMap 存储的为键值对即Key–Value。
Node[] nodes;//数组
class Node {
Object key;
Object Value;
Node next;//链表
}
然后进行查看hashMap源码,进行比对是否一致。
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
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;
}
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
上面的代码片段与我们进行推测的基本一致,代码片段中使用的泛型的形式,而且比推断出来的多了int hash.
hash用来确定存放的位置。
由此可以进行推断出HashMap的数据结构为数组+链表(单向链表)
二、HashMap中的put源码解析
首先
我们已经知道了HashMap的数据结构,那么我们就会产生一些问题?比如HashMap的容量?
我们再次打开HashMap的源码,在属性中看到下面的片段
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
上面的英文注释意思为:“默认初始化容量–必须为2的幂”,默认(DEFAULT_INITIAL_CAPACITY )为即16,下面的为最大容量(MAXIMUM_CAPACITY )为2的30次方。
DEFAULT_LOAD_FACTOR 为加载因子,即方容量达到0.75f 的时候进行扩容。
即16 * 0.75 = 12。
TREEIFY_THRESHOLD 链表的长度,当达到这个长度时进行转换为红黑树。
那么在进行执行put的过程将会如何进行存储的?
2.1、put时会将key,value存储的位置在哪个地方?
我们看到如下:
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
在进行put的时候调用了putVal方法,,而且注释中已经说明,如果map已经存在了该key,那么就会进行覆盖。
第一个参数为key的hash(key),我们进去看下这个方法。
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
这个方法是拿到key的hash值与低16位进行异或。
我们希望得到的是一个长度的值,比如第一次进行put的时候,我们希望一个算法得到将我们的值放在下标为0—15的数组当中,最简单的方法是进行取模运算,对16进行取模,这样得到的下标为0-15。使用二进制进行&操作的效率更快即(hash值&(n-1))可是在实际过程中会产生相同的值。
然而在实际过程中可能会出现相同的下标,此时机会导致冲突的概率增大,导致分布的不均匀。
在JDK1.8的实现中对比进行了优化,优化了高位运算的算法,通过hashCode()的高16位异或低16位实现的:(h = k.hashCode()) ^ (h >>> 16),主要是从速度、功效、质量来考虑的。
同时这样进行了充分的利用位数,导致碰撞的可能性降低。
也是就说在进行hash值&(n-1)时进行,如果n=16,相当于hash & 01111,也就是hash的前28位不管是什么产生的结果都不会有影响,如果进行高16位于低16位进行异或后就会充分利用了每一位,导致碰撞冲突的概率降低。
2.2、为什么长度要是2的幂,而且每次进行扩容时进行翻倍呢?
首先我们进行先看代码
红色的部分就是获取存放的位置,这里是进行位与运算。
在进行位与的运算时,16-1 =15,15用二进制表示为01111,此时后四位为1,保证了不管什么数与之与运算,都不会一直是一个值。简单的说,如果长度为13的话,13-1用二进制表示为1100,那么不管什么数与1100相与,它的最后两位一直未0,这样冲突的概率就会很大。
2.3、put的具体过程
上图为put的过程,下面我们跟着源码进行分析
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判断是否为null,长度是否为0
if ((tab = table) == null || (n = tab.length) == 0)
//是的话进行扩容,如果为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 {
//进行遍历找到next为null的进行存入
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//链表长度过长就会查询慢,临界值为8
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;
}
}
//当不存在时e== null
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//判断是否达到扩容的标准,即长度是否达到75%
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
2.4、resize 扩容(包括初始化)
在进行第一次put的时候以及达到临界值时会进行扩容,但是当达到最大值时会将临界值设置为最大容量。