概述
HashMap 是一个关联数组、哈希表,它是线程不安全的,允许key为null,value为null。遍历时无序。 其底层数据结构是数组称之为哈希桶,每个桶里面放的是链表,链表中的每个节点,就是哈希表中的每个元素。 在JDK8中,当链表长度达到8,会转化成红黑树,以提升它的查询、插入效率,它实现了Map<K,V>, Cloneable, Serializable接口。
因其底层哈希桶的数据结构是数组,所以也会涉及到扩容的问题。
HashMap:1.7之前 24 之前: 数组+ 链表
HashMap:1.8 之后: 数组+ 链表 + 红黑树
Hash碰撞越少 说明散列的越均匀 每个数组元素上链表长度就越短 查找就越快
还有一点需要注意的,那就是HashMap遍历的时候是无序的。后面源码解析
使用
HashMap<String, Object> hashMap = new HashMap<>(10);
hashMap.putIfAbsent("2",new boolean[]);
hashMap.put("dd",new HashMap<>());
hashMap.remove("dddd");
hashMap.remove("ddd",new boolean[]);
hashMap.replace("ddd","dddd")
hashMap.getOrDefault()
源码分析
1、new HashMap<>(10) 分析
public HashMap(int initialCapacity) {
//DEFAULT_LOAD_FACTOR 加载因子 默认值是0.75
//为啥是0.75 参考文章地址 https://zhuanlan.zhihu.com/p/149687607
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
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;
//构造函数 如果传入了值 那么这个时候 阈值是2的幂次方整数 而不是2的幂次方整数*0.75
this.threshold = tableSizeFor(initialCapacity);
}
/**
* HashMap源码中的tableSizeFor(int cap)方法 参考地址https://www.jianshu.com/p/4ed9260d988c
* 返回一个比给定整数大且最接近的2的幂次方整数
* @param cap
* @return
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
加载因子为啥是0.75 参考文章面试官:为什么 HashMap 的加载因子是0.75? 这样的目的是为了最大限度的使用数组空间的同时保证hash冲突最少 就是散列函数的目的
为啥给定数组的长度是2的幂次方整数 可以参考关于hashMap的容量为什么是2的幂次方的最详细解析文章。这个地方 我单独强调的是位运算比取余运算快很多
2、hashMap.putIfAbsent("2",new boolean[])源码分析
@Override
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
注意第三个参数值是true
static final int hash(Object key) {
int h;
//HashMap中hash(Object key)原理,为什么(hashcode >>> 16)
//参考 https://blog.csdn.net/qq_42034205/article/details/90384772
//通过这种形式 扰动函数 使得散列的更均匀
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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;
//关于(n - 1) & hash为什么等于 hash % n https://blog.csdn.net/LeeMon23/article/details/120893190
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)
//树操作 此处不分析 涉及到平衡树跟红黑树 单链表长度大于7即会转变 为了查找更快
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//如果找了一圈都没有 那就插到后面 此时这个地方的值还为null
p.next = newNode(hash, key, value, null);
//如果链表长度大于等于8 那就转成树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果key相等 hash值相等 那就说明找到了 就是e
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//不为null 说明之前这个地方有数据 那这种情况 数据也不需要扩容
if (e != null) { // existing mapping for key
//拿出旧数据
V oldValue = e.value;
//调用putIfAbsent方法 onlyIfAbsent值为true 调用put方法 该值为false
if (!onlyIfAbsent || oldValue == null)
//如果之前数据为null 那就直接将新数据放进去
//或者 如果之前调用的是put方法 那也把新数据放回去 反之 如果调用的是putIfAbsent且之前有数据 那么新数据不会替换
e.value = value;
afterNodeAccess(e);
//都是返回旧数据
return oldValue;
}
}
//修改次数
++modCount;
//如果新增数据 大于阈值 那就重新计算 且把旧数据放到新map里
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
关于(n - 1) & hash为什么等于 hash % n blog.csdn.net/LeeMon23/ar…
扩容方法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) {
if (oldCap >= MAXIMUM_CAPACITY) {
//设置到intger的极限值了
threshold = Integer.MAX_VALUE;
return oldTab;
}
//符合逻辑判断的话 也将数组容器长度先翻倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//新的阈值直接等于旧的阈值2倍
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
//构造函数 如果传入了值 那么这个时候 阈值是2的幂次方整数 而不是2的幂次方整数*0.75
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
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;
}
就是将数组长度翻倍 然后将旧数组数据 挨个挪到新数组中
需要注意 put方法跟putIfAbsent区别
3、hashMap.remove("dddd"); hashMap.remove("ddd",new boolean[]);源码分析 分析方法二即可
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
public boolean remove(Object key, Object value) {
//如果找到节点 那就返回节点
return removeNode(hash(key), key, value, true, true) != null;
}
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 &&
//找到table位置
//p是数组下面第一个值
(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也是数组下面第一个值
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是真实位置
node = e;
break;
}
//p是真实位置前一个节点
p = e;
} while ((e = e.next) != null);
}
}
//找到具体的key相等的节点 matchValue是否要匹配值
//remove(Object key) 这个方法不需要比较value值
//remove(Object key, Object value) 这个方法不仅需要key相等 value也得相等
hashMap.remove("ddd",new boolean[]);
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)
//这说明 当前节点是table[index] 这个链表里的第一个
tab[index] = node.next;
else
//说明不是链表里的第一个
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
//返回找到的节点
return node;
}
}
return null;
}
注意上面方法中 matchValue 变量!!!
4、replace方法
public V replace(K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null) {
//找到节点 返回旧节点value 且把新节点value替换掉节点value
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
//如果key对应节点没有 那么不做任何事情 且返回null
return null;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//通过key找到对应节点
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;
}
getOrDefault
这个注意是让读者注意 这种写法日常比较多
@Override
public V getOrDefault(Object key, V defaultValue) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}
为啥hashMap遍历是无序的呢? 重点!!!
先强调一点,HashMap是怎么取数据的呢?前面分析 我们知道 HashMap是数组+单链表(也会演化成树)。数组中的每一个元素是链表。 我们通过遍历数组的形式 然后依次找到该数组[index]中链表 然后遍历链表。因为插入数据是通过hash值取余运算 那么就会存在 当我们将元素 A B C 插入数组的时候 A C 在数组前面 B在后面 那我们遍历拿出来 就是 A C B,那么就是无序了。
HashMap遍历
Set<Map.Entry<String, Object>> entries =
hashMap.entrySet();
Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
//判断是不是有数据
while (iterator.hasNext()) {
//获取数据
iterator.next()
}
HashMap遍历源码分析
1. hashMap.entrySet()
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
//第一次entrySet是null 那么就是获取EntrySet()
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
EntrySet结构
2.entries.iterator()
拿的就是上图实体类
3.iterator.next() 核心方法 遍历取数据
一样看上图 其实调用的是父类hashiterator的nextNode方法
abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
expectedModCount = modCount;
//table是数组数据
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
//next = t[index++] 这个操作是 初始index =0 next就是= table[0] index = 0+1
do {} while (index < t.length && (next = t[index++]) == null);
}
}
public final boolean hasNext() {
return next != null;
}
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
//如果当前table[index] 只有一个数据了 那就去到table[index+1]初始位置
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
//返回遍历到的节点
return e;
}
参考文章
- HashMap的实现原理及hash冲突解决方法 这篇文章针对hashmap的链表源码分析的很详细了 后面针对平衡树跟红黑树没有讲解
- 【集合系列】- 深入浅出的分析 Hashtable
- 面试必问之 ConcurrentHashMap 线程安全的具体实现方式 ConcurrentHashMap源码分析的非常好
- 万字 HashMap 详解,基础(优雅)永不过时 —— 源码篇 该文章写得非常详细 我没有细看 备日后之用
- 面试必备:HashMap源码解析(JDK8) 这篇文章写得也非常好 值得推荐看!
- 面试官: HashMap 为什么线程不安全?