前言
面试一般都会问到HashMap
整理内容自慕课网
https://coding.imooc.com/lesson/337.html#mid=24128
参考博客:https://www.cnblogs.com/aspirant/p/8906018.html
内容讲的是HashTable,里面数据结构和如何扩容说得挺好
内容
- 图解数据结构
- 图解说明数据结构基础
- 图解说明HashMap原理
- 源码分析
- 源码分析HashMap的创建以及扩容
- 节点的插入、查询与删除
- 如何提高散列以及冲突的解决办法
图解说明HashMap
HashMap是如何实现快速索引的?
数组
数组的本质是一块连续的内存空间,因为内存空间连续,我们只要知道首地址的位置,就能很快定位所有数据,所以数组的有点很明显,就是通过下标可以快速寻址
缺点也是明显的,就是对于有序的数据,如果想要插入,就要移动大量的位置
单链表
node {
T data;
node next;
}
插入删除方便,查询O(n)
HashMap
HashMap既要插入高效,又要查询高效,显然就是结合了数组和链表二者的优点
为了快速定位,又要插入数据,如果保持插入的动作不变,那么为了能够定位,我们就需要知道插入的值和数组下标之间的关系
假设数据是一个int类型的数组
pos = key % size
key就是插入的数据,size是数组的大小,pos就是下标
那么插入和查找的时候都需要通过这个求模操作
但是这很显然有一个问题
两个插入的值100和200对一个size为10的数组求模,得到的结果都是0,这显然是不允许出现的情况
这就涉及到了HashMap的冲突问题
要解决这一冲突,有一个很简单的办法,就是在同一个下标用单链表来进行扩展
就上面的例子来说就是100的这个节点位置有一个指向200的指针
查找时将有一个比较值并且比较其next的过程
那么问题就又绕回来了,单链表查询低效(但其实够用了)
在JDK1.8版本中对这一问题做了优化,将单链表过长的时候将转化为红黑树以提高查询速率,这里不对红黑树做讲解
HashMap源码分析
resize与hash比较
构造一个HashMap
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("100", "test");
}
查看它的构造方法
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
对成员变量loadFactor负载因子赋值0.75f
再来查看HashMap的put操作
/**
* 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);
}
里面是一个putVal
/**
* 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;
}
putVal的几件事情
- 判断table是否为空 进行resize
- hash判断是直接插入还是链表插入
resize方法有三个重要的参数:负载因子、容量、阈值
下面是初始化时的参数
newCap = DEFAULT_INITIAL_CAPACITY; // 1 << 4 aka 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
当当前的table大小超过阈值的时候就会扩容
if (oldCap > 0) {
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
}
扩容是旧的容量左移一位
再看一下它的hash判断
if ((p = tab[i = (n - 1) & hash]) == null)
n是table的大小 大小减1之后hash得到的i(这里涉及hash的计算之后再说 hash自然是根据内容得到的)
面试问题:为什么初始大小为2的倍数
- 最主要的是:2的倍数减1之后会得到后面全为1的二进制位,hash与运算可以有多种结果,即提高散列度
- 通用的,减少内存分页的碎片
- 计算机最擅长与运算等
如何Hash
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
putVal的第一个参数就是hash,那么如何得到这个根据key获取到的hash值呢
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
这里逻辑很简单
- 首先判空,如果为空则直接返回0
- 如果不为空则通过native方法hasCode获取int值
- 与这个值右移十六位之后的结果进行异或运算
这里的异或操作也是为了提高散列度…至于为什么我也不知道
这是面试问题中Hash函数如何减少冲突的一个回答
冲突的解决
其实就是
if ((p = tab[i = (n - 1) & hash]) == null)
这个else里面的内容了
这里简单梳理一下逻辑
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;
}
}
这里有三种可能
- 插入的新节点的hash与key值都与当前节点相同
- 旧节点是一个黑红树的节点
- 旧节点是一个单链表的节点
插入属于数据结构的知识了,这里看一下单链表到红黑树转化的逻辑
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
名字非常直观了 如果单链表的长度超过了树化的阈值那么就进行红黑树化
默认的树化阈值为8
扩容与非扩容后的内存排布
来分析一下resize
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
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
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;
前面都在进行初始化
如果oldTable是有值的,那么就要把oldTable的节点给复制到newTable
这里有三个判断
- e.next == null 也就是没有冲突的情况
- e instanceof TreeNode 冲突解决是红黑树的形式
- 冲突解决是单链表的形式
分支选择来完成复制
- 没有冲突
newTab[e.hash & (newCap - 1)] = e;
根据hash来确定位置 这里的下标是newCap-1来hash的,这和putVal的hash判断一致
2. 红黑树的split 略
3. 单链表的处理
//如果扩容后,元素的index依然与原来一样,那么使用这个head和tail指针
Node<K,V> loHead = null, loTail = null
//如果扩容后,元素的index=index+oldCap,那么使用这个head和tail指针
Node<K,V> hiHead = null, hiTail = null
Node<K,V> next;
do {
next = e.next;
//这个地方直接通过hash值与oldCap进行与操作得出元素在新数组的index
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
//tail指针往后移动一位,维持顺序
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
//tail指针往后移动一位,维持顺序
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
//还是原来的index
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
//index = index + oldCap
newTab[j + oldCap] = hiHead;
这里这么做可以保证它与旧的链表顺序相同
HashMap的查询
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("100", "test");
map.get("100");
}
/**
* 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;
}
调用getNode方法
/**
* 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 {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
这里也没什么特别的,就和平时写业务逻辑的代码一样判空之类操作
若都不为空为比较key值,若first不等则分别按照红黑树和单链表来继续比较
HashMap删除
/**
* 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;
}
看一下removeNode
/**
* 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;
}
删除的逻辑开始和查找一样,找到之后获取这个node
然后分别根据无冲突、黑红树、单链表三种分支来操作删除
共同需要做的就是–size等
HashMap的序列化
HashMap的序列化主要是调用了writeObject方法