南宁网站seo外包,品牌推广三元论,企业官网门户网站管理系统,建设一个公司网站要具备什么系列文章目录
[Java基础] StringBuffer 和 StringBuilder 类应用及源码分析 [Java基础] 数组应用及源码分析 [Java基础] String#xff0c;分析内存地址#xff0c;源码 [JDK8环境下的HashMap类应用及源码分析] 第一篇 空构造函数初始化 [JDK8环境下的HashMap类应用及源码分…系列文章目录
[Java基础] StringBuffer 和 StringBuilder 类应用及源码分析 [Java基础] 数组应用及源码分析 [Java基础] String分析内存地址源码 [JDK8环境下的HashMap类应用及源码分析] 第一篇 空构造函数初始化 [JDK8环境下的HashMap类应用及源码分析] 第二篇 看源码了解HashMap的扩容机制 [JDK8环境下的HashMap类应用及源码分析] 第三篇 修改capacity实验 [JDK8环境下的HashMap类应用及源码分析] 第四篇 HashMap哈希碰撞、HashMap存储结构、链表变红黑树 文章目录 系列文章目录1、JDK8下的HashMap的数据结构1.1、hash1.2、key、value类型1.3、Node1.4、TreeNode1.5、插入数据时的数据结构变化 2、实验2.1、哈希碰撞2.1.1、与位运算()2.1.2、哈希碰撞 2.2、链表变红黑树 1、JDK8下的HashMap的数据结构
HashMap是一种基于数组和链表或红黑树的数据结构它通过哈希函数将键映射到数组的一个位置并在该位置存储一个键值对的节点。 HashMap的put方法在插入数据前首先要计算键的哈希值hash(key)和索引然后在相应的位置插入或更新节点如果节点数超过阈值threshold就会进行扩容(resize())或树化。 HashMap的get方法主要是根据键的哈希值和索引找到对应的位置然后遍历链表或红黑树返回匹配的值。
1.1、hash
public class HashMap {static final int hash(Object key) {int h;return (key null) ? 0 : (h key.hashCode()) ^ (h 16);}
}public class Object {public native int hashCode();
}public final class System {/*** Returns the same hash code for the given object as* would be returned by the default method hashCode(),* whether or not the given objects class overrides* hashCode().* The hash code for the null reference is zero.** param x object for which the hashCode is to be calculated* return the hashCode* since JDK1.1*/public static native int identityHashCode(Object x);}
下文引用自深入解析Java对象和类在HotSpot VM内部的具体实现 对象哈希值 _mark中有一个hash code字段表示对象的哈希值。每个Java对象都有自己的哈希值如果没有重写Object.hashCode()方法那么虚拟机会为它自动生成一个哈希值。哈希值生成的策略如代码清单3-4所示 代码清单3-4 对象hash值生成策略 static inline intptr_t get_next_hash(Thread * Self, oop obj) { intptr_t value 0; if (hashCode 0) { // Park-Miller随机数生成器 value os::random(); } else if (hashCode 1) { // 每次STW时生成stwRandom做随机 intptr_t addrBits cast_from_oop Java层调用Object.hashCode()或者System.identityHashCode()最终会调用虚拟机层的runtime/synchronizer的get_next_hash()生成哈希值。 1.2、key、value类型 static final int TREEIFY_THRESHOLD 8; //链表转红黑树final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {NodeK,V[] tab; NodeK,V p; int n, i;//判断table是否初始化if ((tab table) null || (n tab.length) 0)//如果是调用 resize() 方法进行初始化并赋值n (tab resize()).length;//通过hash获取下标如果数据为nullif ((p tab[i (n - 1) hash]) null)// tab[i]下标没有值创建新的Node并赋值tab[i] newNode(hash, key, value, null);else {//tab[i] 下标的有数据发生碰撞NodeK,V e; K k;//判断tab[i]的hash值和传入的hash值相同tab[i]的的key值和传入的key值相同if (p.hash hash ((k p.key) key || (key ! null key.equals(k))))//如果是key值相同直接替换即可e p;else if (p instanceof TreeNode)//判断数据结构为红黑树e ((TreeNodeK,V)p).putTreeVal(this, tab, hash, key, value);else {//数据结构是链表for (int binCount 0; ; binCount) {//p的下一个节点为null,表示p就是最后一个节点if ((e p.next) null) {//创建新的Node节点并插入链表的尾部p.next newNode(hash, key, value, null);//当元素8-1链表转为树(红黑树)结构if (binCount TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash);break;}//如果key在链表中已经存在则退出循环if (e.hash hash ((k e.key) key || (key ! null key.equals(k))))break;//更新p指向下一个节点继续遍历p e;}}//如果key在链表中已经存在则修改其原先key的value值并且返回老的value值if (e ! null) {V oldValue e.value;if (!onlyIfAbsent || oldValue null)e.value value;afterNodeAccess(e);//替换旧值时会调用的方法(默认实现为空)return oldValue;}}modCount;//修改次数//根据map值判断是否要对map的大小扩容if (size threshold)resize();afterNodeInsertion(evict);//插入成功时会调用的方法(默认实现为空)return null;}查看putVal源码key、vlaue数据类型使用泛型任意引用类型都可以Java基础类型不可以因为基本数据类型不能调用其hashcode()方法和equals()方法,进行比较,所以HashMap集合的key只能为引用数据类型,不能为基本数据类型,可以使用基本数据类型的包装类,例如Integer、Double、Long、Float等。
1.3、Node
见【1.2】代码部分tab变量的类型Node实现了Map.Entry接口 Node里有hash、key、value等属性也有next下一个节点变量链表 Node实现了toString、hashCode、equals等方法
static class NodeK,V implements Map.EntryK,V {final int 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; }public final int hashCode() {return Objects.hashCode(key) ^ Objects.hashCode(value);}public final V setValue(V newValue) {V oldValue value;value newValue;return oldValue;}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;}
}interface EntryK,V {K getKey();V getValue();V setValue(V value);boolean equals(Object o);int hashCode();public static K extends Comparable? super K, V ComparatorMap.EntryK,V comparingByKey() {return (ComparatorMap.EntryK, V Serializable)(c1, c2) - c1.getKey().compareTo(c2.getKey());}public static K, V extends Comparable? super V ComparatorMap.EntryK,V comparingByValue() {return (ComparatorMap.EntryK, V Serializable)(c1, c2) - c1.getValue().compareTo(c2.getValue());}public static K, V ComparatorMap.EntryK, V comparingByKey(Comparator? super K cmp) {Objects.requireNonNull(cmp);return (ComparatorMap.EntryK, V Serializable)(c1, c2) - cmp.compare(c1.getKey(), c2.getKey());}public static K, V ComparatorMap.EntryK, V comparingByValue(Comparator? super V cmp){Objects.requireNonNull(cmp);return (ComparatorMap.EntryK, V Serializable)(c1, c2) - cmp.compare(c1.getValue(), c2.getValue());}
}1.4、TreeNode
见【1.2】代码部分p变量的类型TreeNode实现了LinkedHashMap.Entry接口 TreeNode里有red等属性也有parent、left、right、prev等变量(红黑树) TreeNode实现了treeify、find、putTreeVal等方法
static final class TreeNodeK,V extends LinkedHashMap.EntryK,V {TreeNodeK,V parent; // red-black tree linksTreeNodeK,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;}}static K,V void moveRootToFront(NodeK,V[] tab, TreeNodeK,V root) {...}final TreeNodeK,V find(int h, Object k, Class? kc) {TreeNodeK,V p this;do {int ph, dir; K pk;TreeNodeK,V pl p.left, pr p.right, q;if ((ph p.hash) h)p pl;else if (ph h)p pr;else if ((pk p.key) k || (k ! null k.equals(pk)))return p;else if (pl null)p pr;else if (pr null)p pl;else if ((kc ! null ||(kc comparableClassFor(k)) ! null) (dir compareComparables(kc, k, pk)) ! 0)p (dir 0) ? pl : pr;else if ((q pr.find(h, k, kc)) ! null)return q;elsep pl;} while (p ! null);return null;}final TreeNodeK,V getTreeNode(int h, Object k) {return ((parent ! null) ? root() : this).find(h, k, null);}static int tieBreakOrder(Object a, Object b) {int d;if (a null || b null ||(d a.getClass().getName().compareTo(b.getClass().getName())) 0)d (System.identityHashCode(a) System.identityHashCode(b) ?-1 : 1);return d;}final void treeify(NodeK,V[] tab) {TreeNodeK,V root null;for (TreeNodeK,V x this, next; x ! null; x next) {next (TreeNodeK,V)x.next;x.left x.right null;if (root null) {x.parent null;x.red false;root x;}else {K k x.key;int h x.hash;Class? kc null;for (TreeNodeK,V p root;;) {int dir, ph;K pk p.key;if ((ph p.hash) h)dir -1;else if (ph h)dir 1;else if ((kc null (kc comparableClassFor(k)) null) ||(dir compareComparables(kc, k, pk)) 0)dir tieBreakOrder(k, pk);TreeNodeK,V xp p;if ((p (dir 0) ? p.left : p.right) null) {x.parent xp;if (dir 0)xp.left x;elsexp.right x;root balanceInsertion(root, x);break;}}}}moveRootToFront(tab, root);}final NodeK,V untreeify(HashMapK,V map) {NodeK,V hd null, tl null;for (NodeK,V q this; q ! null; q q.next) {NodeK,V p map.replacementNode(q, null);if (tl null)hd p;elsetl.next p;tl p;}return hd;}/*** Tree version of putVal.*/final TreeNodeK,V putTreeVal(HashMapK,V map, NodeK,V[] tab,int h, K k, V v) {Class? kc null;boolean searched false;TreeNodeK,V root (parent ! null) ? root() : this;for (TreeNodeK,V p root;;) {int dir, ph; K pk;if ((ph p.hash) h)dir -1;else if (ph h)dir 1;else if ((pk p.key) k || (k ! null k.equals(pk)))return p;else if ((kc null (kc comparableClassFor(k)) null) ||(dir compareComparables(kc, k, pk)) 0) {if (!searched) {TreeNodeK,V q, ch;searched true;if (((ch p.left) ! null (q ch.find(h, k, kc)) ! null) ||((ch p.right) ! null (q ch.find(h, k, kc)) ! null))return q;}dir tieBreakOrder(k, pk);}TreeNodeK,V xp p;if ((p (dir 0) ? p.left : p.right) null) {NodeK,V xpn xp.next;TreeNodeK,V x map.newTreeNode(h, k, v, xpn);if (dir 0)xp.left x;elsexp.right x;xp.next x;x.parent x.prev xp;if (xpn ! null)((TreeNodeK,V)xpn).prev x;moveRootToFront(tab, balanceInsertion(root, x));return null;}}}final void removeTreeNode(HashMapK,V map, NodeK,V[] tab,boolean movable) {...}final void split(HashMapK,V map, NodeK,V[] tab, int index, int bit) {...}/* ------------------------------------------------------------ */// Red-black tree methods, all adapted from CLRstatic K,V TreeNodeK,V rotateLeft(TreeNodeK,V root,TreeNodeK,V p) {...return root;}static K,V TreeNodeK,V rotateRight(TreeNodeK,V root,TreeNodeK,V p) {...return root;}static K,V TreeNodeK,V balanceInsertion(TreeNodeK,V root,TreeNodeK,V x) {...}static K,V TreeNodeK,V balanceDeletion(TreeNodeK,V root,TreeNodeK,V x) {...}static K,V boolean checkInvariants(TreeNodeK,V t) {...return true;}}1.5、插入数据时的数据结构变化
见【1.2】代码在插入数据时数据结构有什么变化呢 效果图可见【1】里的第二张图
判断table是否初始化 是-调用 resize() 方法进行初始化并赋值如果不是初始化通过hash获取下标如果数据为null tab[i]下标没有值创建新的Node并赋值tab[i] 下标的有数据发生hash碰撞有3种情况 1、判断tab[i]的hash值和传入的hash值相同tab[i]的的key值和传入的key值相同 如果相同直接替换 2、判断数据结构为红黑树 调用红黑树的数据插入函数putTreeVal 3、数据结构是链表 循环链表如果p的下一个节点为null,表示p就是最后一个节点此时在尾部插入新Node节点如果此时元素个数大于等于7链表转为红黑树结构 如果key在链表中已经存在则退出循环
2、实验
实验里包括哈希碰撞和链表变红黑树让我们一步步Debug跟踪源代码探个究竟
2.1、哈希碰撞
2.1.1、与位运算()
1、计算字符串A , “B” , “C” , “D” , “E” , “F” , “G” , H的hashCode2、转换为2进制https://jisuan5.com/decimal/?hex356573597 十进制的15转换2进制结果:1111 此实验中A的hashCode356573597,十进制的356573597转换2进制结果:10101010000001110000110011101 356573597 15 10101010000001110000110011101 1111 10101010000001110000110011101 00000000000000000000000001111高位补码0对齐左边的数据 00000000000000000000000001101 1101高位的0可以省略掉3、经过多次把15(2的4次方-1)改为其他数据的实验我们发现2的幂次方-1低位都是1在做与位运算时数据会平均分布改为2的幂次方或其他数据低位存在0最终数据分布不均匀 int n 16 - 1; //二进制: 1111String[] strs { A , B , C , D , E , F , G , H};for (int i 0; i strs.length; i) {System.out.println(-------------------------);System.out.println(System.identityHashCode(strs[i]) );System.out.println(二进制 Integer.toBinaryString(System.identityHashCode(strs[i])) );System.out.println( System.identityHashCode(strs[i]) n );System.out.println(-------------------------);}
-------------------------
356573597
二进制10101010000001110000110011101
13
-------------------------
-------------------------
1735600054
二进制1100111011100110010011110110110
6
-------------------------
-------------------------
21685669
二进制1010010101110010110100101
5
-------------------------
-------------------------
2133927002
二进制1111111001100010010010001011010
10
-------------------------
-------------------------
1836019240
二进制1101101011011110110111000101000
8
-------------------------
-------------------------
325040804
二进制10011010111111011101010100100
4
-------------------------
-------------------------
1173230247
二进制1000101111011100001001010100111
7
-------------------------
-------------------------
856419764
二进制110011000010111110110110110100
4
-------------------------2.1.2、哈希碰撞
在【2.1.1】的代码案例中F、H的哈希值与15进行与位运算后值都是4详细解释见【1.5】, 相当于计算在HashMap里的索引位置
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {...if ((p tab[i (n - 1) hash]) null)...
}在此给出几种解决哈希碰撞哈希冲突的解决办法
链地址法 遇到哈希碰撞的数据在数组里索引相同然后使用链表去存储发生碰撞的数据JDK8的HashMap采用的此方法且使用的尾插法。再哈希法 当遇到哈希碰撞问题时在此哈希直到冲突不在产生这种方法不易产生聚集但是增加了计算时间开放地址法 当遇到哈希碰撞问题时从发生冲突的那个单元起按照一定的次序从哈希表中找到一个空闲的单元。然后把发生冲突的元素存入到该单元的一种方法。建立公共溢出区 将哈希表分为公共表和溢出表当溢出发生时将所有溢出数据统一放到溢出区
2.2、链表变红黑树
给定2个假设在HashMap里默认加载因子0.75在大于1216*0.7512长度时就会扩容成32与位运算重新计算值也会变更重新均衡的分布详细解释见【1.5】
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {...//p的下一个节点为null,表示p就是最后一个节点if ((e p.next) null) {//创建新的Node节点并插入链表的尾部p.next newNode(hash, key, value, null);//当元素8-1链表转为树(红黑树)结构if (binCount TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash);break;}...
}
1、哈希桶不扩容 2、(F、H…H8 ) 15 都等于4,总共9个元素在第7个元素加入时会触发链表转红黑树H7、H8插入时直接走红黑树插入逻辑 文章转载自: http://www.morning.rxnr.cn.gov.cn.rxnr.cn http://www.morning.bpmfz.cn.gov.cn.bpmfz.cn http://www.morning.mmtbn.cn.gov.cn.mmtbn.cn http://www.morning.rdmn.cn.gov.cn.rdmn.cn http://www.morning.pbdnj.cn.gov.cn.pbdnj.cn http://www.morning.kmqlf.cn.gov.cn.kmqlf.cn http://www.morning.slqzb.cn.gov.cn.slqzb.cn http://www.morning.rfrxt.cn.gov.cn.rfrxt.cn http://www.morning.htbbp.cn.gov.cn.htbbp.cn http://www.morning.ckdgj.cn.gov.cn.ckdgj.cn http://www.morning.qdbcd.cn.gov.cn.qdbcd.cn http://www.morning.xkwyk.cn.gov.cn.xkwyk.cn http://www.morning.bfgpn.cn.gov.cn.bfgpn.cn http://www.morning.pgrsf.cn.gov.cn.pgrsf.cn http://www.morning.gcqdp.cn.gov.cn.gcqdp.cn http://www.morning.rhmpk.cn.gov.cn.rhmpk.cn http://www.morning.qpnmd.cn.gov.cn.qpnmd.cn http://www.morning.vtbtje.cn.gov.cn.vtbtje.cn http://www.morning.tdnbw.cn.gov.cn.tdnbw.cn http://www.morning.lfdmf.cn.gov.cn.lfdmf.cn http://www.morning.xxknq.cn.gov.cn.xxknq.cn http://www.morning.hytr.cn.gov.cn.hytr.cn http://www.morning.ryrgx.cn.gov.cn.ryrgx.cn http://www.morning.ppzgr.cn.gov.cn.ppzgr.cn http://www.morning.wngpq.cn.gov.cn.wngpq.cn http://www.morning.kdjtt.cn.gov.cn.kdjtt.cn http://www.morning.qrqdr.cn.gov.cn.qrqdr.cn http://www.morning.dmtbs.cn.gov.cn.dmtbs.cn http://www.morning.dpsgq.cn.gov.cn.dpsgq.cn http://www.morning.lngyd.cn.gov.cn.lngyd.cn http://www.morning.lmzpk.cn.gov.cn.lmzpk.cn http://www.morning.kqwsy.cn.gov.cn.kqwsy.cn http://www.morning.kzrbn.cn.gov.cn.kzrbn.cn http://www.morning.qhrdx.cn.gov.cn.qhrdx.cn http://www.morning.lwqst.cn.gov.cn.lwqst.cn http://www.morning.mbzlg.cn.gov.cn.mbzlg.cn http://www.morning.fnpmf.cn.gov.cn.fnpmf.cn http://www.morning.lwmzp.cn.gov.cn.lwmzp.cn http://www.morning.zwgrf.cn.gov.cn.zwgrf.cn http://www.morning.fxqjz.cn.gov.cn.fxqjz.cn http://www.morning.hmxrs.cn.gov.cn.hmxrs.cn http://www.morning.gcqs.cn.gov.cn.gcqs.cn http://www.morning.bmmhs.cn.gov.cn.bmmhs.cn http://www.morning.ejknty.cn.gov.cn.ejknty.cn http://www.morning.qcfgd.cn.gov.cn.qcfgd.cn http://www.morning.phjyb.cn.gov.cn.phjyb.cn http://www.morning.plqqp.cn.gov.cn.plqqp.cn http://www.morning.qnbgh.cn.gov.cn.qnbgh.cn http://www.morning.nzklw.cn.gov.cn.nzklw.cn http://www.morning.qmkyp.cn.gov.cn.qmkyp.cn http://www.morning.lwnwl.cn.gov.cn.lwnwl.cn http://www.morning.rknhd.cn.gov.cn.rknhd.cn http://www.morning.lgtzd.cn.gov.cn.lgtzd.cn http://www.morning.fbmzm.cn.gov.cn.fbmzm.cn http://www.morning.rmfh.cn.gov.cn.rmfh.cn http://www.morning.mtrrf.cn.gov.cn.mtrrf.cn http://www.morning.sxcwc.cn.gov.cn.sxcwc.cn http://www.morning.qhln.cn.gov.cn.qhln.cn http://www.morning.rkmsm.cn.gov.cn.rkmsm.cn http://www.morning.wsrcy.cn.gov.cn.wsrcy.cn http://www.morning.qkrgk.cn.gov.cn.qkrgk.cn http://www.morning.xqbgm.cn.gov.cn.xqbgm.cn http://www.morning.bhqlj.cn.gov.cn.bhqlj.cn http://www.morning.lxqyf.cn.gov.cn.lxqyf.cn http://www.morning.lmtbl.cn.gov.cn.lmtbl.cn http://www.morning.bpmdx.cn.gov.cn.bpmdx.cn http://www.morning.kzdwt.cn.gov.cn.kzdwt.cn http://www.morning.mlmwl.cn.gov.cn.mlmwl.cn http://www.morning.jzccn.cn.gov.cn.jzccn.cn http://www.morning.rgmd.cn.gov.cn.rgmd.cn http://www.morning.rkkh.cn.gov.cn.rkkh.cn http://www.morning.mpnff.cn.gov.cn.mpnff.cn http://www.morning.aishuxue.com.cn.gov.cn.aishuxue.com.cn http://www.morning.rzpkt.cn.gov.cn.rzpkt.cn http://www.morning.fglth.cn.gov.cn.fglth.cn http://www.morning.sgpny.cn.gov.cn.sgpny.cn http://www.morning.qtryb.cn.gov.cn.qtryb.cn http://www.morning.tjcgl.cn.gov.cn.tjcgl.cn http://www.morning.fbjnr.cn.gov.cn.fbjnr.cn http://www.morning.bzkgn.cn.gov.cn.bzkgn.cn