jdk源码-hashMap源码解读
2021/12/20 20:23:34
本文主要是介绍jdk源码-hashMap源码解读,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
hashmap源码解读
文章目录
- hashmap源码解读
- 一、HashMap1.8源码解读
- 二、解读内容
- 1.初始值
- 2.Put解读
- 2.ReSize解读
- 2.HashMap构造函数解读
- 总结
一、HashMap1.8源码解读
二、解读内容
1.初始值
代码如下(示例):
/** * The default initial capacity - MUST be a power of two. * 默认的初始化容量,必须是2的幂 */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. * 最大容量, */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load factor used when none specified in constructor. * 负载因子,主要是计算能容纳的最大元素 * 计算公式 threshold = 初始化capacity * loadFactor */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. * 链表转换为红黑树的阀值 */ static final int TREEIFY_THRESHOLD = 8; /** * The bin count threshold for untreeifying a (split) bin during a * resize operation. Should be less than TREEIFY_THRESHOLD, and at * most 6 to mesh with shrinkage detection under removal. * 红黑树转换为链表的阀值,扩容时才能发生 */ static final int UNTREEIFY_THRESHOLD = 6; /** * The smallest table capacity for which bins may be treeified. * (Otherwise the table is resized if too many nodes in a bin.) * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. * 进行树化的最小容量,防止在调整容量和形态时发生冲突 * 4 * TREEIFY_THRESHOLD */ static final int MIN_TREEIFY_CAPACITY = 64;
2.Put解读
代码如下(示例):
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; //i = (n - 1) & hash,数组的位置,就是当前位置的元素为空,则往数组赋值 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; //如果当前key=key,直接覆盖元素 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); //如果链表长度>=7,8是阈值,直接转换为红黑树 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } //如果链表匹配了key,直接覆盖 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; }
2.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; //如果老的容量>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 } //旧的大于0,直接将旧的赋值给新的 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) { //先将旧的元素的数组引用置空,便于jvm-回收 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 //链表有值>1 Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; //java8很巧妙,不用重新计算新的index值,由于是2的n次方,扩容前是 1111,扩容后index是11111, // 所以值hash*(n-1)的值相比于原数组要么是 01111,11111,取决于hash值,也就是最高位, //最高位是0,则数组坐标不变,最高位是1,则数组位置是=10000+原坐标=原长度+原坐标 //此表达式,目的是为了该元素在新旧数组的小标是否相同 // (oldCap - 1) * e.hash = (2 * oldCap - 1) * e.hash=oldCap * e.hash = 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); if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
2.HashMap构造函数解读
代码如下(示例):
public HashMap(int initialCapacity, float loadFactor) { //初始化的值小于0,直接抛异常 if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); //初始化的值大于最大容量,初始化值等于定义的最大容量 if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; //加载因子小于等于0,抛异常 if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; //重新计算数组大小,赋值的大小如果不是2的n次方,则转换为2的n次方 this.threshold = tableSizeFor(initialCapacity); }
总结
hashMap,1.8虽然相对于1.7优化了很多,解决了扩容时,链表成环的弊端,主要也是设计上优化了很多,1,7采用头插法,1,8尾插法以及在链表上移动元素时的一些计算,不建议多线程使用hashMap.这篇关于jdk源码-hashMap源码解读的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南