曲阜网站建设多少钱,不用vip也能看的黄台的app,湛江模板建站公司,产业互联网排名HashMap 简介底层数据结构分析 JDK1.8 之前JDK1.8 之后 HashMap 源码分析 构造方法put 方法get 方法resize 方法 HashMap 常用方法测试 感谢 changfubai 对本文的改进做出的贡献#xff01; HashMap 简介
HashMap 主要用来存放键值对#xff0c;它基于哈希表的 Map 接口实现…HashMap 简介底层数据结构分析 JDK1.8 之前JDK1.8 之后 HashMap 源码分析 构造方法put 方法get 方法resize 方法 HashMap 常用方法测试 感谢 changfubai 对本文的改进做出的贡献 HashMap 简介
HashMap 主要用来存放键值对它基于哈希表的 Map 接口实现是常用的 Java 集合之一。
JDK1.8 之前 HashMap 由 数组链表 组成的数组是 HashMap 的主体链表则是主要为了解决哈希冲突而存在的“拉链法”解决冲突。
JDK1.8 之后 HashMap 的组成多了红黑树在满足下面两个条件之后会执行链表转红黑树操作以此来加快搜索速度。
链表长度大于阈值默认为 8HashMap 数组长度超过 64
底层数据结构分析
JDK1.8 之前
JDK1.8 之前 HashMap 底层是 数组和链表 结合在一起使用也就是 链表散列。
HashMap 通过 key 的 hashCode 经过扰动函数处理过后得到 hash 值然后通过 (n - 1) hash 判断当前元素存放的位置这里的 n 指的是数组的长度如果当前位置存在元素的话就判断该元素与要存入的元素的 hash 值以及 key 是否相同如果相同的话直接覆盖不相同就通过拉链法解决冲突。
所谓扰动函数指的就是 HashMap 的 hash 方法。使用 hash 方法也就是扰动函数是为了防止一些实现比较差的 hashCode() 方法 换句话说使用扰动函数之后可以减少碰撞。
JDK 1.8 HashMap 的 hash 方法源码:
JDK 1.8 的 hash 方法 相比于 JDK 1.7 hash 方法更加简化但是原理不变。 static final int hash(Object key) {int h;// key.hashCode()返回散列值也就是hashcode// ^ 按位异或// :无符号右移忽略符号位空位都以0补齐return (key null) ? 0 : (h key.hashCode()) ^ (h 16);}对比一下 JDK1.7 的 HashMap 的 hash 方法源码.
static int hash(int h) {// This function ensures that hashCodes that differ only by// constant multiples at each bit position have a bounded// number of collisions (approximately 8 at default load factor).h ^ (h 20) ^ (h 12);return h ^ (h 7) ^ (h 4);
}相比于 JDK1.8 的 hash 方法 JDK 1.7 的 hash 方法的性能会稍差一点点因为毕竟扰动了 4 次。
所谓 “拉链法” 就是将链表和数组相结合。也就是说创建一个链表数组数组中每一格就是一个链表。若遇到哈希冲突则将冲突的值加到链表中即可。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cwUL252F-1677050195849)(https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/jdk1.8之前的内部结构.png)]
JDK1.8 之后
相比于之前的版本JDK1.8 以后在解决哈希冲突时有了较大的变化。
当链表长度大于阈值默认为 8时会首先调用 treeifyBin()方法。这个方法会根据 HashMap 数组来决定是否转换为红黑树。只有当数组长度大于或者等于 64 的情况下才会执行转换红黑树操作以减少搜索时间。否则就是只是执行 resize() 方法对数组扩容。相关源码这里就不贴了重点关注 treeifyBin()方法即可 类的属性
public class HashMapK,V extends AbstractMapK,V implements MapK,V, Cloneable, Serializable {// 序列号private static final long serialVersionUID 362498820763181265L;// 默认的初始容量是16static final int DEFAULT_INITIAL_CAPACITY 1 4;// 最大容量static final int MAXIMUM_CAPACITY 1 30;// 默认的填充因子static final float DEFAULT_LOAD_FACTOR 0.75f;// 当桶(bucket)上的结点数大于这个值时会转成红黑树static final int TREEIFY_THRESHOLD 8;// 当桶(bucket)上的结点数小于这个值时树转链表static final int UNTREEIFY_THRESHOLD 6;// 桶中结构转化为红黑树对应的table的最小大小static final int MIN_TREEIFY_CAPACITY 64;// 存储元素的数组总是2的幂次倍transient Nodek,v[] table;// 存放具体元素的集transient Setmap.entryk,v entrySet;// 存放元素的个数注意这个不等于数组的长度。transient int size;// 每次扩容和更改map结构的计数器transient int modCount;// 临界值 当实际大小(容量*填充因子)超过临界值时会进行扩容int threshold;// 加载因子final float loadFactor;
}loadFactor 加载因子 loadFactor 加载因子是控制数组存放数据的疏密程度loadFactor 越趋近于 1那么 数组中存放的数据(entry)也就越多也就越密也就是会让链表的长度增加loadFactor 越小也就是趋近于 0数组中存放的数据(entry)也就越少也就越稀疏。 loadFactor 太大导致查找元素效率低太小导致数组的利用率低存放的数据会很分散。loadFactor 的默认值为 0.75f 是官方给出的一个比较好的临界值。 给定的默认容量为 16负载因子为 0.75。Map 在使用过程中不断的往里面存放数据当数量达到了 16 * 0.75 12 就需要将当前 16 的容量进行扩容而扩容这个过程涉及到 rehash、复制数据等操作所以非常消耗性能。 threshold threshold capacity * loadFactor当 Sizethreshold的时候那么就要考虑对数组的扩增了也就是说这个的意思就是 衡量数组是否需要扩增的一个标准。
Node 节点类源码:
// 继承自 Map.EntryK,V
static class NodeK,V implements Map.EntryK,V {final int hash;// 哈希值存放元素到hashmap中时用来与其他元素hash值比较final K key;//键V value;//值// 指向下一个节点NodeK,V next;Node(int hash, K key, V value, NodeK,V next) {this.hash hash;this.key key;this.value value;this.next next;}public final K getKey() { return key; }public final V getValue() { return value; }public final String toString() { return key value; }// 重写hashCode()方法public final int hashCode() {return Objects.hashCode(key) ^ Objects.hashCode(value);}public final V setValue(V newValue) {V oldValue value;value newValue;return oldValue;}// 重写 equals() 方法public final boolean equals(Object o) {if (o this)return true;if (o instanceof Map.Entry) {Map.Entry?,? e (Map.Entry?,?)o;if (Objects.equals(key, e.getKey()) Objects.equals(value, e.getValue()))return true;}return false;}
}树节点类源码:
static final class TreeNodeK,V extends LinkedHashMap.EntryK,V {TreeNodeK,V parent; // 父TreeNodeK,V left; // 左TreeNodeK,V right; // 右TreeNodeK,V prev; // needed to unlink next upon deletionboolean red; // 判断颜色TreeNode(int hash, K key, V val, NodeK,V next) {super(hash, key, val, next);}// 返回根节点final TreeNodeK,V root() {for (TreeNodeK,V r this, p;;) {if ((p r.parent) null)return r;r p;}HashMap 源码分析
构造方法
HashMap 中有四个构造方法它们分别如下 // 默认构造函数。public HashMap() {this.loadFactor DEFAULT_LOAD_FACTOR; // all other fields defaulted}// 包含另一个“Map”的构造函数public HashMap(Map? extends K, ? extends V m) {this.loadFactor DEFAULT_LOAD_FACTOR;putMapEntries(m, false);//下面会分析到这个方法}// 指定“容量大小”的构造函数public HashMap(int initialCapacity) {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;this.threshold tableSizeFor(initialCapacity);}putMapEntries 方法
final void putMapEntries(Map? extends K, ? extends V m, boolean evict) {int s m.size();if (s 0) {// 判断table是否已经初始化if (table null) { // pre-size// 未初始化s为m的实际元素个数float ft ((float)s / loadFactor) 1.0F;int t ((ft (float)MAXIMUM_CAPACITY) ?(int)ft : MAXIMUM_CAPACITY);// 计算得到的t大于阈值则初始化阈值if (t threshold)threshold tableSizeFor(t);}// 已初始化并且m元素个数大于阈值进行扩容处理else if (s threshold)resize();// 将m中的所有元素添加至HashMap中for (Map.Entry? extends K, ? extends V e : m.entrySet()) {K key e.getKey();V value e.getValue();putVal(hash(key), key, value, false, evict);}}
}put 方法
HashMap 只提供了 put 用于添加元素putVal 方法只是给 put 方法调用的一个方法并没有提供给用户使用。
对 putVal 方法添加元素的分析如下
如果定位到的数组位置没有元素 就直接插入。如果定位到的数组位置有元素就和要插入的 key 比较如果 key 相同就直接覆盖如果 key 不相同就判断 p 是否是一个树节点如果是就调用e ((TreeNodeK,V)p).putTreeVal(this, tab, hash, key, value)将元素添加进入。如果不是就遍历链表插入(插入的是链表尾部)。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Cxqqocoy-1677050195851)(https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/put方法.png)]
说明:上图有两个小问题
直接覆盖之后应该就会 return不会有后续操作。参考 JDK8 HashMap.java 658 行issue#608。当链表长度大于阈值默认为 8并且 HashMap 数组长度超过 64 的时候才会执行链表转红黑树的操作否则就只是对数组扩容。参考 HashMap 的 treeifyBin() 方法issue#1087。
public V put(K key, V value) {return putVal(hash(key), key, value, false, true);
}final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {NodeK,V[] tab; NodeK,V p; int n, i;// table未初始化或者长度为0进行扩容if ((tab table) null || (n tab.length) 0)n (tab resize()).length;// (n - 1) hash 确定元素存放在哪个桶中桶为空新生成结点放入桶中(此时这个结点是放在数组中)if ((p tab[i (n - 1) hash]) null)tab[i] newNode(hash, key, value, null);// 桶中已经存在元素else {NodeK,V e; K k;// 比较桶中第一个元素(数组中的结点)的hash值相等key相等if (p.hash hash ((k p.key) key || (key ! null key.equals(k))))// 将第一个元素赋值给e用e来记录e p;// hash值不相等即key不相等为红黑树结点else if (p instanceof TreeNode)// 放入树中e ((TreeNodeK,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);// 结点数量达到阈值(默认为 8 )执行 treeifyBin 方法// 这个方法会根据 HashMap 数组来决定是否转换为红黑树。// 只有当数组长度大于或者等于 64 的情况下才会执行转换红黑树操作以减少搜索时间。否则就是只是对数组扩容。if (binCount TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash);// 跳出循环break;}// 判断链表中结点的key值与插入的元素的key值是否相等if (e.hash hash ((k e.key) key || (key ! null key.equals(k))))// 相等跳出循环break;// 用于遍历桶中的链表与前面的e p.next组合可以遍历链表p e;}}// 表示在桶中找到key值、hash值与插入元素相等的结点if (e ! null) {// 记录e的valueV oldValue e.value;// onlyIfAbsent为false或者旧值为nullif (!onlyIfAbsent || oldValue null)//用新值替换旧值e.value value;// 访问后回调afterNodeAccess(e);// 返回旧值return oldValue;}}// 结构性修改modCount;// 实际大小大于阈值则扩容if (size threshold)resize();// 插入后回调afterNodeInsertion(evict);return null;
}我们再来对比一下 JDK1.7 put 方法的代码
对于 put 方法的分析如下
① 如果定位到的数组位置没有元素 就直接插入。② 如果定位到的数组位置有元素遍历以这个元素为头结点的链表依次和插入的 key 比较如果 key 相同就直接覆盖不同就采用头插法插入元素。
public V put(K key, V value)if (table EMPTY_TABLE) {inflateTable(threshold);
}if (key null)return putForNullKey(value);int hash hash(key);int i indexFor(hash, table.length);for (EntryK,V e table[i]; e ! null; e e.next) { // 先遍历Object k;if (e.hash hash ((k e.key) key || key.equals(k))) {V oldValue e.value;e.value value;e.recordAccess(this);return oldValue;}}modCount;addEntry(hash, key, value, i); // 再插入return null;
}get 方法
public V get(Object key) {NodeK,V e;return (e getNode(hash(key), key)) null ? null : e.value;
}final NodeK,V getNode(int hash, Object key) {NodeK,V[] tab; NodeK,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) {// 在树中getif (first instanceof TreeNode)return ((TreeNodeK,V)first).getTreeNode(hash, key);// 在链表中getdo {if (e.hash hash ((k e.key) key || (key ! null key.equals(k))))return e;} while ((e e.next) ! null);}}return null;
}resize 方法
进行扩容会伴随着一次重新 hash 分配并且会遍历 hash 表中所有的元素是非常耗时的。在编写程序中要尽量避免 resize。
final NodeK,V[] resize() {NodeK,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;}// 没超过最大值就扩充为原来的2倍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 thresholdnewCap oldThr;else {// signifies using defaultsnewCap DEFAULT_INITIAL_CAPACITY;newThr (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);}// 计算新的resize上限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})NodeK,V[] newTab (NodeK,V[])new Node[newCap];table newTab;if (oldTab ! null) {// 把每个bucket都移动到新的buckets中for (int j 0; j oldCap; j) {NodeK,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)((TreeNodeK,V)e).split(this, newTab, j, oldCap);else {NodeK,V loHead null, loTail null;NodeK,V hiHead null, hiTail null;NodeK,V next;do {next e.next;// 原索引if ((e.hash oldCap) 0) {if (loTail null)loHead e;elseloTail.next e;loTail e;}// 原索引oldCapelse {if (hiTail null)hiHead e;elsehiTail.next e;hiTail e;}} while ((e next) ! null);// 原索引放到bucket里if (loTail ! null) {loTail.next null;newTab[j] loHead;}// 原索引oldCap放到bucket里if (hiTail ! null) {hiTail.next null;newTab[j oldCap] hiHead;}}}}}return newTab;
}HashMap 常用方法测试
package map;import java.util.Collection;
import java.util.HashMap;
import java.util.Set;public class HashMapDemo {public static void main(String[] args) {HashMapString, String map new HashMapString, String();// 键不能重复值可以重复map.put(san, 张三);map.put(si, 李四);map.put(wu, 王五);map.put(wang, 老王);map.put(wang, 老王2);// 老王被覆盖map.put(lao, 老王);System.out.println(-------直接输出hashmap:-------);System.out.println(map);/*** 遍历HashMap*/// 1.获取Map中的所有键System.out.println(-------foreach获取Map中所有的键:------);SetString keys map.keySet();for (String key : keys) {System.out.print(key );}System.out.println();//换行// 2.获取Map中所有值System.out.println(-------foreach获取Map中所有的值:------);CollectionString values map.values();for (String value : values) {System.out.print(value );}System.out.println();//换行// 3.得到key的值的同时得到key所对应的值System.out.println(-------得到key的值的同时得到key所对应的值:-------);SetString keys2 map.keySet();for (String key : keys2) {System.out.print(key map.get(key) );}/*** 如果既要遍历key又要value那么建议这种方式因为如果先获取keySet然后再执行map.get(key)map内部会执行两次遍历。* 一次是在获取keySet的时候一次是在遍历所有key的时候。*/// 当我调用put(key,value)方法的时候首先会把key和value封装到// Entry这个静态内部类对象中把Entry对象再添加到数组中所以我们想获取// map中的所有键值对我们只要获取数组中的所有Entry对象接下来// 调用Entry对象中的getKey()和getValue()方法就能获取键值对了Setjava.util.Map.EntryString, String entrys map.entrySet();for (java.util.Map.EntryString, String entry : entrys) {System.out.println(entry.getKey() -- entry.getValue());}/*** HashMap其他常用方法*/System.out.println(after map.size()map.size());System.out.println(after map.isEmpty()map.isEmpty());System.out.println(map.remove(san));System.out.println(after map.remove()map);System.out.println(after map.get(si)map.get(si));System.out.println(after map.containsKey(si)map.containsKey(si));System.out.println(after containsValue(李四)map.containsValue(李四));System.out.println(map.replace(si, 李四2));System.out.println(after map.replace(si, 李四2):map);}} 文章转载自: http://www.morning.ktfnj.cn.gov.cn.ktfnj.cn http://www.morning.rdgb.cn.gov.cn.rdgb.cn http://www.morning.leboju.com.gov.cn.leboju.com http://www.morning.hkcjx.cn.gov.cn.hkcjx.cn http://www.morning.nnttr.cn.gov.cn.nnttr.cn http://www.morning.fcxt.cn.gov.cn.fcxt.cn http://www.morning.nptls.cn.gov.cn.nptls.cn http://www.morning.lsxabc.com.gov.cn.lsxabc.com http://www.morning.nicetj.com.gov.cn.nicetj.com http://www.morning.bgkk.cn.gov.cn.bgkk.cn http://www.morning.ljdhj.cn.gov.cn.ljdhj.cn http://www.morning.jrwbl.cn.gov.cn.jrwbl.cn http://www.morning.ryrgx.cn.gov.cn.ryrgx.cn http://www.morning.sftpg.cn.gov.cn.sftpg.cn http://www.morning.pcwzb.cn.gov.cn.pcwzb.cn http://www.morning.krtky.cn.gov.cn.krtky.cn http://www.morning.nkiqixr.cn.gov.cn.nkiqixr.cn http://www.morning.cxryx.cn.gov.cn.cxryx.cn http://www.morning.yxyyp.cn.gov.cn.yxyyp.cn http://www.morning.duqianw.com.gov.cn.duqianw.com http://www.morning.rfgkf.cn.gov.cn.rfgkf.cn http://www.morning.qbwmz.cn.gov.cn.qbwmz.cn http://www.morning.dwfxl.cn.gov.cn.dwfxl.cn http://www.morning.lpppg.cn.gov.cn.lpppg.cn http://www.morning.myzfz.com.gov.cn.myzfz.com http://www.morning.dyhlm.cn.gov.cn.dyhlm.cn http://www.morning.gtnyq.cn.gov.cn.gtnyq.cn http://www.morning.dyrzm.cn.gov.cn.dyrzm.cn http://www.morning.qflwp.cn.gov.cn.qflwp.cn http://www.morning.xpqsk.cn.gov.cn.xpqsk.cn http://www.morning.wzwyz.cn.gov.cn.wzwyz.cn http://www.morning.qttft.cn.gov.cn.qttft.cn http://www.morning.tqklh.cn.gov.cn.tqklh.cn http://www.morning.lmjtp.cn.gov.cn.lmjtp.cn http://www.morning.tllws.cn.gov.cn.tllws.cn http://www.morning.sltfk.cn.gov.cn.sltfk.cn http://www.morning.rjrh.cn.gov.cn.rjrh.cn http://www.morning.ppwdh.cn.gov.cn.ppwdh.cn http://www.morning.srbl.cn.gov.cn.srbl.cn http://www.morning.jlnlr.cn.gov.cn.jlnlr.cn http://www.morning.hytr.cn.gov.cn.hytr.cn http://www.morning.rjnrf.cn.gov.cn.rjnrf.cn http://www.morning.rsjf.cn.gov.cn.rsjf.cn http://www.morning.kqblk.cn.gov.cn.kqblk.cn http://www.morning.nzhzt.cn.gov.cn.nzhzt.cn http://www.morning.qwqzk.cn.gov.cn.qwqzk.cn http://www.morning.kjrlp.cn.gov.cn.kjrlp.cn http://www.morning.hqqpy.cn.gov.cn.hqqpy.cn http://www.morning.hsjfs.cn.gov.cn.hsjfs.cn http://www.morning.wmmjw.cn.gov.cn.wmmjw.cn http://www.morning.amonr.com.gov.cn.amonr.com http://www.morning.tpmnq.cn.gov.cn.tpmnq.cn http://www.morning.mjxgs.cn.gov.cn.mjxgs.cn http://www.morning.xpqsk.cn.gov.cn.xpqsk.cn http://www.morning.zknjy.cn.gov.cn.zknjy.cn http://www.morning.drmbh.cn.gov.cn.drmbh.cn http://www.morning.krqhw.cn.gov.cn.krqhw.cn http://www.morning.lkfsk.cn.gov.cn.lkfsk.cn http://www.morning.xqmd.cn.gov.cn.xqmd.cn http://www.morning.dphmj.cn.gov.cn.dphmj.cn http://www.morning.nrrzw.cn.gov.cn.nrrzw.cn http://www.morning.cwznh.cn.gov.cn.cwznh.cn http://www.morning.jpnfm.cn.gov.cn.jpnfm.cn http://www.morning.mrlkr.cn.gov.cn.mrlkr.cn http://www.morning.gpfuxiu.cn.gov.cn.gpfuxiu.cn http://www.morning.jspnx.cn.gov.cn.jspnx.cn http://www.morning.qxltp.cn.gov.cn.qxltp.cn http://www.morning.ktmbp.cn.gov.cn.ktmbp.cn http://www.morning.lsssx.cn.gov.cn.lsssx.cn http://www.morning.blqmn.cn.gov.cn.blqmn.cn http://www.morning.hxlpm.cn.gov.cn.hxlpm.cn http://www.morning.kmcfw.cn.gov.cn.kmcfw.cn http://www.morning.nrmyj.cn.gov.cn.nrmyj.cn http://www.morning.itvsee.com.gov.cn.itvsee.com http://www.morning.skwwj.cn.gov.cn.skwwj.cn http://www.morning.wrkhf.cn.gov.cn.wrkhf.cn http://www.morning.xyrw.cn.gov.cn.xyrw.cn http://www.morning.fynkt.cn.gov.cn.fynkt.cn http://www.morning.pbwcq.cn.gov.cn.pbwcq.cn http://www.morning.gprzp.cn.gov.cn.gprzp.cn