废话不多说,先上图:
Map接口之HashMap(最常用)
基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。
1.结构图
2.底层结构
//底层实现 在list中链表是一个值 这里是KV键值对 一个map由N多个Node组成
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //hash值
final K key; //key
V value; //value
Node<K,V> next; //hash碰撞时,存储在链表的下一个节点中
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
3.构造方法
//new HashMap<>()
public HashMap() {
//static final float DEFAULT_LOAD_FACTOR = 0.75f; 默认加载因子0.75
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//new HashMap(10)
this(initialCapacity, DEFAULT_LOAD_FACTOR); //DEFAULT_LOAD_FACTOR = -.75
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);
//0.75
this.loadFactor = loadFactor;
//官方翻译 返回给定目标容量的两个大小的幂 默认值的话是16*0.75
//(int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY)
this.threshold = tableSizeFor(initialCapacity);
}
4.put添加元素
public V put(K key, V value) {
//先看下hash计算规则 ###
return putVal(hash(key), key, value, false, true);
}
//hash计算规则
static final int hash(Object key) {
int h;
//key的hashCode 右移16位 >>>表示不区分正反
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//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;
//table还未初始化
if ((tab = table) == null || (n = tab.length) == 0)
//初始化和扩容都会走resize 等会重点看
n = (tab = resize()).length;
//通过hash在tab中取值,就是那个坑是否有萝卜了
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))))
//重复put走这里 直接取值
e = p;
else if (p instanceof TreeNode)
//红黑树链
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//处理链表
for (int binCount = 0; ; ++binCount) {
//当前链表是否有下一个node同时赋值给e
if ((e = p.next) == null) {
//没有的话 直接把当前元素塞到该链表的下一个元素里面
//当这里执行完成后 debug看tab实际上是看不到当前put的元素的
//因为不是在链表中的第一个
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//如果链表长度大于等于7(0开始的,其实就是8), 就转换红黑树
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//put之前已有链表就返回链表的值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//操作完成size+1 如果大于当前升级数threshold 就走扩容流程
if (++size > threshold)
//扩容 ###
resize();
afterNodeInsertion(evict);
return null;
}
5.扩容方法 resize
前面说到初始化和扩容都走的是同一个方法 resize,让我们看下有何神奇之处吧
//扩容方法
final Node<K,V>[] resize() {
//赋值当前tab
Node<K,V>[] oldTab = table;
//当前tab的size
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//当前tab的升级数
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
//只有扩容才进这里 容量大于 1<<30 直接设置成最大值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//当前容量<<1 就是2倍 最大数字> oldCap*2 >>默认容量16 并赋值给新容量newCap
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
//默认的 16 容量
newCap = DEFAULT_INITIAL_CAPACITY;
//升级数 16*0.75=12
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) {
//处理当前tab
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
//只存在一个链表的时候 直接给新tab赋值
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;
//根据e.hash & oldCap这个算法分成两类
//例如:25 & 98 = 0 25->0001 1001 98->0110 0010 最终为0
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);
//等于0时,新数组的存放位置与旧数组存放位置一致,记未低位区链表lo开头low
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
//不等于0的,新数组位置等于旧数组索引加上旧数组容量,记为高位区链表hi开头high
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
6.get获取元素
//map.get("xxx")
public V get(Object key) {
Node<K,V> e;
//先计算hash值
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//getNode 获取链表node
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 {//链表的do while取值
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
//把下一个节点赋值给e 再比较hash和key值
} while ((e = e.next) != null);
}
}
return null;
}
7.remove删除元素
//map.remove("xxxx")
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
//removeNode
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;
//取到的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);
}
}
//目标节点上下节点的直通 返回目标节点
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;
}
常见问题
HashMap源码分析就到此结束了,需要深入了解的自己去!
找了点常面试的问题,在这里记录下
1.为什么长度要是2的n次方?
为了存储高效,减少碰撞,就是要尽量把数据分配均匀,每个链表长度大致相同,这个实现就在把数据存到哪个链表中的算法;
这个算法实际就是取模,hash%length,计算机中直接求余效率不如位移运算,源码中做了优化hash&(length-1),
hash%length==hash&(length-1)的前提是length是2的n次方;
为什么这样能均匀分布减少碰撞呢?2的n次方实际就是1后面n个0,2的n次方-1 实际就是n个1;
HashMap计算添加元素的位置时,使用的位运算,这是特别高效的运算;另外,HashMap的初始容量是2的n次幂,扩容也是2倍的形式进行扩容,是因为容量是2的n次幂,可以使得添加的元素均匀分布在HashMap中的数组上,减少hash碰撞,避免形成链表的结构,使得查询效率降低!
以上就是 Map接口 – HashMap源码分析篇 的全部内容了。
下一篇我们开始 Map接口 --TreeMap源码分析
心无杂念则静,心无旁骛则清