数据结构之HashMap
一、链表散列
定义:通过数组和链表结合在一起使用,就叫链表散列。
结构图:
二、HashMap 的数据结构和存储原理:
数据结构:用的就是链表散列,如上图所示。JDK1.8:是数组+链表+红黑树
如何存储?
1.HashMap内部有一个entry的内部类,其中有四个属性,要存储一个值,则需要一个·key和一个value,存到map中就会先将key和value保存在这个Entry类创建的对象中。
源码如下:
对应的物理模型:
2.构造好了entry 对象,然后将该对象放入数组中。
思考:如何将entry 对象放到数组中?(重点)
大概过程:通过entry 对象中的hash值来确定将该对象放在数组的哪个位置,如果这个位置有其他元素,则通过链表来存储这个元素。
三、HashMap 的加载因子loadFactor:
loadFactor是控制数组存放数据的疏密程度的,越趋近于1,数组中存放的数据也就越多,即越密,链表也越长;loadFactor越趋近于0,数组中存放的数据越少,即有可能数组中每个位置上就放一个元素。
加载因子越大,性能越差。因为通过key得到value的过程本质上是:先通过key的hashcode值,找到对应数组中的位置,如果该位置有多个元素,则需要通过equals来依次比较链表中的元素,拿到value值。
加载因子越小,越浪费空间。当数组上的每个位置只放一个元素时,虽然能直接得到value值,但是数据分散的太开。默认的加载因子是0.75。
加载因子=size/capacity。
思考:为什么默认的加载因子是0.75?
当加载因子为0.75时,Entry单链表的长度几乎不可能超过8(到达8的概率为0.00000006),用是让Entry单链表的长度尽量小,让查询效率尽可能高 。
四、HashMap中的一些常用属性:
1.约定上面数组结构中的每一格子称为桶;
2.约定桶中存放的每一个数据称为bin。(jdk1.8的注释)
3.size:表示HashMap中实际存放KV(即entry对象)的数量。
4.capacity:指HashMap中桶的数量,默认1 << 4,第一次扩容会扩到64(为了避免冲突。Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts between resizing and treeification thresholds
),之后是2倍。总之容量都是2的幂。
思考:为什么容量一定要是2的幂次方?
因为HashMap是数组+单链表的结构,我们希望元素存放的更加均匀,最理想的状态是每个Entry中只放一个元素,这样查询效率最高。那么怎么样才能均匀的存放呢?首先想到的就是取模运算:哈希地址%容量大小,但大师们用的是位运算(位运算效率高),为了是位运算和取模结果一样,即hash & (capacity-1) == hash % capacity
,容量的大小就必须为2的幂次方。
5.threshold: 表示当HashMap 的size大于threshold时,会执行resize操作。threshold=capacity*loadFactor
6.table :是一个Entry[ ] 数组类型,而Entry实际上是一个单项链表,哈希表的键值对都是存在Entry数组中,每个Entry(即桶)对应一个hash地址。
7.modCount: 用来实现快速失败机制
对于线程不安全(注:只是线程不安全的集合才哟偶这个机制)的集合对象的迭代器,如果在使用迭代器的过程中有其他线程修改了集合对象的结构或者元素数量,那么迭代立刻结束。
五、HashMap有四个构造函数:
1.无参构造函数,load factor=0.75
/** Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
2.指定HashMap 容量大小的的构造函数,load factor is 0.75
/** Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
3.指定HashMap容量大小和负载因子的构造函数
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
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);
}
4.包含子Map的构造函数,load factor is 0.75
/**
* Constructs a new <tt>HashMap</tt> with the same mappings as the
* specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
* default load factor (0.75) and an initial capacity sufficient to
* hold the mappings in the specified <tt>Map</tt>.
*
* @param m the map whose mappings are to be placed in this map
* @throws NullPointerException if the specified map is null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
六、put 方法
在JDK1.8之前HashMap的插入是在链表的头部插入的,而JDK1.8的源码,是在链表的尾部插入的。
- 根据键(key)的hashCode()计算出当前键值对的哈希地址,用于定位键值对在HashMap数组中存储的下标
- 判断 table是否初始化,没有初始化则调用resize()为table 初始化容量,以及threshold的值。
- 根据table数组的长度和哈希地址做&运算
(i = (n-1) & hash)
计算出该key对应的table数组索引,如果对应的数组索引位置没有值,则调用newNode(hash,key,value,null)
方法,为该键值对创建节点。
思考: 为什么不直接按照哈希地址做数组下标,而是用table数组的长度和哈希地址做&运算(i = (n-1) & hash)
? - 根据哈希地址计算出该key对应的table数组索引有节点,且节点的键key和传入的键key相等,哈希地址和传入的哈希地址也相等,则将对应的节点引用赋值给e。
- 如果根据哈希地址计算出该key对应的table数组索引有节点,且节点的哈希地址和传入的哈希地址一样,但是节点的键key和传入的key不相等,则遍历链表,如果遍历过程中找到找到节点的键key和传入的键key相等,哈希地址和传入的哈希地址也相等,则将对应的value值更新。否则调用
newNode(hash,key,value,null)
方法,为该键值对创建节点添加到链表尾部,如果追加节点后的链表长度>=8,则转为红黑树。 - 如果e不为空,且onlyIfAbsent 为true,则不回覆盖相同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);
}
/**
* 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
*/
//如果参数onlyIfAbsent is true,那么不会覆盖相同key的value,如果evict是false,那么表示是在初始化时调用的
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//tab 存放 当前的哈希桶, p用作临时链表节点
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果当前哈希表是空的,代表是初始化
if ((tab = table) == null || (n = tab.length) == 0)
//直接扩容哈希表,并且将扩容后的哈希桶的长度赋值给n
n = (tab = resize()).length;
//那么如果当前index的节点是空,表示没有发生哈希冲突,直接构建一个新节点Node,挂载在index处即可。
//切记:数组下标index,是利用哈希地址 & 哈希桶的长度-1 ,替代模运算
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {//否则· 发生哈希冲突
Node<K,V> e; K k;
//如果哈希值相等,key也相等,则是覆盖value操作
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;//当前节点引用赋值给e
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);
//如果追加节点后,链表数量>=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;
}
}
//如果不是null,说明有需要覆盖的节点
if (e != null) { // existing mapping for key
//覆盖节点值,并返回oldValue
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);//这是一个空实现的函数,用作LinkedHashMap重写使用
return oldValue;
}
}
//执行到这里,表示插入了一个新节点,所以会修改modCount,并返回null
++modCount;
if (++size > threshold)//更新size,并判断是否需要扩容
resize();
afterNodeInsertion(evict);
return null;
}
七、Get()方法:
- table不为空,且table长度大于0,且根据键key的hashCode()计算出哈希地址,再根据
(i = (n-1) & hash)
计算出数组下标,该下标不为空(即存在链表头指针),则继续往下进行,否则返回null - 如果和第一个节点的哈希地址、键key都相同,则返回第一个节点
- 如果第一个节点的下一个节点不为空,则继续,如果第一个节点为数的节点,则执行
getTreeNode(hash, key);
在树中找节点,并返回。否则遍历链表,找到键key和、哈希地址一样的则返回此节点。
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
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 {//在链表中get
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
八、remove()方法 :
- table不为空,且table长度大于0,且根据键key的hashCode()计算出哈希地址,再根据
(i = (n-1) & hash)
计算出数组下标,该下标不为空(即存在链表头指针),则继续往下进行,否则执行6. - 如果哈希地址一样、键key一样,则将对应的节点引用赋值给node,然后执行4,否则执行6.
- 如果为树,则执行
getTreeNode(hash, key);
在树中找节点,并返回。否则遍历链表,找到键key、哈希地址一样的节点,然后将对应的节点引用赋值给node,然后执行4,否则执行6 - 如果节点node不为空(即查到键key对应的节点)且当matchValue为false的时候或者value也相等时,则执行5,否则执行6
- 如果节点为树,则调用
removeTreeNode(this, tab, movable);
移除相应节点。都则执行6 - 返回null。
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key key whose mapping is to be removed from the map
* @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 remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* Implements Map.remove and related methods
*
* @param hash hash for key
* @param key the 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;
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;
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);
}
}
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;
}
九、containKey()方法:
如果存在key,则返回true,否则返回false。
十、哈希表的初始化和加倍扩容后resize方法:
分析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;
//如果哈希表是空的,则将旧容量置为0,否则置为旧哈希表的容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold; //旧的哈希表的阈值
int newCap, newThr = 0;//新的哈希表的容量和阈值 都置为0
if (oldCap > 0) {//如果就的容量大于0
//旧的容量是否大于2的30次幂值,即容量的最大值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;//阈值设为Integer的最大值
return oldTab;//返回旧的哈希表,旧的哈希表达到最大容量,不能扩容了,所以返回
}
//新的哈希表的容量=旧的容量<<1,即2倍,如果新的容量小于容量的最大值,且旧的容量大于等于默认的容量
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//扩容table,即新的阈值=旧的2倍
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
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<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) {
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 { // preserve order
//将旧的哈希表的节点全部重新定位,比如旧的哈希表的容量为16,有一个值a放在数组下标为0上,新的哈新表的容量为32,
//重新定位后值a就被重新定位到下标为32上,即新的下标=旧的下标+新的哈希表的容量,正是因为这个节点的迁移,所以在hasmap put/get操作时,在哈希表容量发生变化后仍能取到正确的值,但是也是因为这个迁移操作,会消耗很多资源。故尽量不让它扩容
//这里的迁移也是使用的位运算,故在初始化的时候,桶的数量必须是2的幂次方,才能保证模运算和位运算结果一样。
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
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;
}
时间复杂度:
O(1):计算时间与数据量大小没有关系,是常量
O(logN):计算时间与数据量成对数关系:例如平衡二叉树
O(N):计算时间与数据量成线性正比关系,例如链表
问题1:为什么jdk1.8之后单链表有头插法改成了尾插法?
因为头插法在并发情况下,扩容的时候,会出现死循环
问题2:为什么使用红黑树,而不是普通的二叉树
因为二叉树在极端情况下会变成链表,时间复杂度变为O(n),红黑树是相对平衡的二叉树,性能较好,能做到时间复杂度为O(logN).
红黑树,通过变色和自旋维持平衡,由任意节点到其字节的最长的路径不会超过其最短路径的2倍
严格的平衡树AVL,左子树和右子树高度差的绝对值不会超过1
问题3:扩容的时候,单链表是怎么移动的?
先创建一个新的数组,判断bin是否为空,不为空,判断bin中是不是只有一个元素,或者是红黑树,或者是单链表,当为单链表的时候,拿哈希值和旧的数组大小做与运算,并判断结果为不为0,为0,那么就将数据移到新数组中和旧数组对应的位置(即原来是j的位置,在新数组中也是j的位置,newTab[j] = loHead;
);不为0,将数据移到新数组中和旧数组对应的位置+旧数组大小的位置(即原先在j位置,扩容后在j+oldCap上,newTab[j + oldCap] = hiHead;
)
{
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 { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
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;
}
}
}