作者主页:青花锁 简介:Java领域优质创作者、Java微服务架构公号作者、CSDN博客专家
简历模板、学习资料、面试题库、技术互助文末获取联系方式
[Java基础] StringBuffer 和 StringBuilder 类应用及源码分析
[Java基础] 数组应用及源码分析
[Java基础] String,分析内存地址,源码
[JDK8环境下的HashMap类应用及源码分析] 第一篇 空构造函数初始化
[JDK8环境下的HashMap类应用及源码分析] 第二篇 看源码了解HashMap的扩容机制
map里的元素数量:0
初始化阶段,threshold是 int类型的默认值0,此时的map下一次触发扩容的阈值:0
map下一次触发扩容的真实阈值比率:0.75
map的容量:16
------------------------------------
map里的元素数量:1
map下一次触发扩容的阈值:12
map下一次触发扩容的真实阈值比率:0.75
map的容量:16
------------------------------------
map里的元素数量:11
map下一次触发扩容的阈值:12
map下一次触发扩容的阈值比率:0.75
map的容量:16
------------------------------------
map里的元素数量:12
map下一次触发扩容的阈值:12
map下一次触发扩容的阈值比率:0.75
map的容量:16
------------------------------------
map里的元素数量:13
map下一次触发扩容的阈值:24
map下一次触发扩容的阈值比率:0.75
map的容量:32
------------------------------------
public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException, InvocationTargetException, IllegalAccessException {
HashMap map = new HashMap<>();
//获取HashMap整个类
Class<?> hashMapClszz = map.getClass();
//获取指定属性,也可以调用getDeclaredFields()方法获取属性数组
Field threshold = hashMapClszz.getDeclaredField("threshold");
//将目标属性设置为可以访问
threshold.setAccessible(true);
Field loadFactor = hashMapClszz.getDeclaredField("loadFactor");
loadFactor.setAccessible(true);
//获取指定方法,因为HashMap没有容量这个属性,但是capacity方法会返回容量值
Method capacity = hashMapClszz.getDeclaredMethod("capacity");
//设置目标方法为可访问
capacity.setAccessible(true);
//打印刚初始化的HashMap的元素数量、阈值、容量
System.out.println("map里的元素数量:" + map.size() );
System.out.println("初始化阶段,threshold是 int类型的默认值0,此时的map下一次触发扩容的阈值:" + threshold.get(map) );
System.out.println("map下一次触发扩容的真实阈值比率:" + loadFactor.get(map) );
System.out.println("map的容量:" + capacity.invoke(map) );
System.out.println("------------------------------------");
map.put(100 , 100);
System.out.println("map里的元素数量:" + map.size() );
System.out.println("map下一次触发扩容的阈值:" + threshold.get(map) );
System.out.println("map下一次触发扩容的真实阈值比率:" + loadFactor.get(map) );
System.out.println("map的容量:" + capacity.invoke(map) );
System.out.println("------------------------------------");
for (int i = 0; i < 10; i++) {
map.put(i , i);
}
System.out.println("map里的元素数量:" + map.size() );
System.out.println("map下一次触发扩容的阈值:" + threshold.get(map) );
System.out.println("map下一次触发扩容的阈值比率:" + loadFactor.get(map) );
System.out.println("map的容量:" + capacity.invoke(map) );
System.out.println("------------------------------------");
map.put(12 , 12);
System.out.println("map里的元素数量:" + map.size() );
System.out.println("map下一次触发扩容的阈值:" + threshold.get(map) );
System.out.println("map下一次触发扩容的阈值比率:" + loadFactor.get(map) );
System.out.println("map的容量:" + capacity.invoke(map) );
System.out.println("------------------------------------");
map.put(13 , 13);
System.out.println("map里的元素数量:" + map.size() );
System.out.println("map下一次触发扩容的阈值:" + threshold.get(map) );
System.out.println("map下一次触发扩容的阈值比率:" + loadFactor.get(map) );
System.out.println("map的容量:" + capacity.invoke(map) );
System.out.println("------------------------------------");
}
备注:HashMap也提供有参的构造函数,可以修改loadFactor等
HashMap map = new HashMap<>();
我们在这里创建一个HashMap对象
查看HashMap源代码,有threshold、loadFactor属性,有capacity、loadFactor方法。后续的loadFactor我们就直接使用属性,代码也只截取了属性
/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
final int capacity() {
return (table != null) ? table.length :
(threshold > 0) ? threshold :
DEFAULT_INITIAL_CAPACITY;
}
//获取HashMap整个类
Class<?> hashMapClszz = map.getClass();
//获取指定属性,也可以调用getDeclaredFields()方法获取属性数组
Field threshold = hashMapClszz.getDeclaredField("threshold");
//将目标属性设置为可以访问
threshold.setAccessible(true);
Field loadFactor = hashMapClszz.getDeclaredField("loadFactor");
loadFactor.setAccessible(true);
//获取指定方法,因为HashMap没有容量这个属性,但是capacity方法会返回容量值
Method capacity = hashMapClszz.getDeclaredMethod("capacity");
//设置目标方法为可访问
capacity.setAccessible(true);
//属性的语法
Field.get(实例化对象)
//方法的语法
Method.invoke(实例化对象)
//打印刚初始化的HashMap的元素数量、阈值、容量
System.out.println("map里的元素数量:" + map.size() );
System.out.println("初始化阶段,threshold是 int类型的默认值0,此时的map下一次触发扩容的阈值:" + threshold.get(map) );
System.out.println("map下一次触发扩容的真实阈值比率:" + loadFactor.get(map) );
System.out.println("map的容量:" + capacity.invoke(map) );
System.out.println("------------------------------------");
结果:
map里的元素数量:0
初始化阶段,threshold是 int类型的默认值0,此时的map下一次触发扩容的阈值:0
map下一次触发扩容的真实阈值比率:0.75
map的容量:16
------------------------------------
查看空构造函数源代码,看看做了哪些操作
/**
* Constructs an empty HashMap with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
int threshold;
final float loadFactor;
transient int size;
transient Node<K,V>[] table;
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
见4.2,size此时值为0
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map
*/
public int size() {
return size;
}
见4.2,threshold此时值为0
见4.2,loadFactor此时值为0.75
见4.2,table此时=null,threshold=0,DEFAULT_INITIAL_CAPACITY=16
三元运算此时结果为16
final int capacity() {
return (table != null) ? table.length :
(threshold > 0) ? threshold :
DEFAULT_INITIAL_CAPACITY;
}
map.put(100 , 100);
System.out.println("map里的元素数量:" + map.size() );
System.out.println("map下一次触发扩容的阈值:" + threshold.get(map) );
System.out.println("map下一次触发扩容的真实阈值比率:" + loadFactor.get(map) );
System.out.println("map的容量:" + capacity.invoke(map) );
System.out.println("------------------------------------");
结果:
map里的元素数量:1
map下一次触发扩容的阈值:12
map下一次触发扩容的真实阈值比率:0.75
map的容量:16
------------------------------------
/**
* 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 key, or
* null if there was no mapping for key.
* (A null return can also indicate that the map
* previously associated null with key.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
入参 key哈希、key、value、onlyIfAbsent、evict(最后2个参数忽略)
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
/**
* 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;
}
/**
* 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;
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;
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;
}
for (int i = 0; i < 10; i++) {
map.put(i , i);
}
System.out.println("map里的元素数量:" + map.size() );
System.out.println("map下一次触发扩容的阈值:" + threshold.get(map) );
System.out.println("map下一次触发扩容的阈值比率:" + loadFactor.get(map) );
System.out.println("map的容量:" + capacity.invoke(map) );
System.out.println("------------------------------------");
结果:
map里的元素数量:11
map下一次触发扩容的阈值:12
map下一次触发扩容的阈值比率:0.75
map的容量:16
------------------------------------
map.put(12 , 12);
System.out.println("map里的元素数量:" + map.size() );
System.out.println("map下一次触发扩容的阈值:" + threshold.get(map) );
System.out.println("map下一次触发扩容的阈值比率:" + loadFactor.get(map) );
System.out.println("map的容量:" + capacity.invoke(map) );
System.out.println("------------------------------------");
结果:
map里的元素数量:12
map下一次触发扩容的阈值:12
map下一次触发扩容的阈值比率:0.75
map的容量:16
------------------------------------
map.put(13 , 13);
System.out.println("map里的元素数量:" + map.size() );
System.out.println("map下一次触发扩容的阈值:" + threshold.get(map) );
System.out.println("map下一次触发扩容的阈值比率:" + loadFactor.get(map) );
System.out.println("map的容量:" + capacity.invoke(map) );
System.out.println("------------------------------------");
结果:
map里的元素数量:13
map下一次触发扩容的阈值:24
map下一次触发扩容的阈值比率:0.75
map的容量:32
------------------------------------
capacity:HashMap的容量,即哈希表中桶的数量。在创建HashMap时,可以指定初始容量,如果不指定,默认为16。当哈希表中的元素数量达到容量的75%时,会触发扩容操作。
threshold:HashMap的阈值,即哈希表中元素数量的上限。当哈希表中元素数量达到阈值时,会触发扩容操作。阈值的计算公式为:threshold = capacity * loadFactor。其中,loadFactor是负载因子,它的默认值为0.75。
size:HashMap中元素的数量。当向HashMap中添加元素时,size会自动增加;当从HashMap中删除元素时,size会自动减少。
modCount:HashMap的修改次数。当向HashMap中添加或删除元素时,modCount会自动增加。在迭代HashMap时,如果发现modCount发生变化,则会抛出ConcurrentModificationException异常,防止在迭代过程中修改HashMap导致数据不一致的问题。
大家点赞、收藏、关注、评论啦 、查看微信公众号获取联系
WX:biancheng2019
精彩专栏推荐:
构建SpringCloud alibaba项目
Vue3实战
构建SpringBoot 项目
JavaScript小游戏
Java基础
博物馆管理系统实战