ps:本博客基于jdk1.8
学习要点:
1、知道hashmap的数据结构人事是做什么的
2、了解hashmap中的散列算法
3、知道hashmap中put、remove、get的代码实现
4、hashmap的哈希冲突是什么?怎么处理的?
5、知道hashmap的扩容机制
1、什么是hashmap?
hashmap 基于哈希表的 map 接口实现,是以 key-value 存储形式存在 ,hashmap 的实现不是同步的,这意味着它不是线程安全的。它的 key、value 都可以为 null,此外,hashmap 中的映射不是有序的。
2、hashmap的特性
hash存储无序的key和value都可以存储null值,但是key只能存唯一的一个null值jdk8之前的数据结构是数组+链表,jdk8之后变成数组+链表+红黑树阀值大于8并且数组长度大于64才会转为红黑树3、hashmap的数据结构
jdk7的情况,是数组加链接,hash冲突时候,就转换为链表:
jdk8的情况,jdk8加上了红黑树,链表的数量大于8而且数组长度大于64之后,就转换为红黑树,红黑树节点小于6之后,就又转换为链表:
翻下hashmap源码,对应的节点信息:
static class node<k,v> implements map.entry<k,v> { // hashcode final int hash; final k key; v value; // 链表的next指针就不为null node<k,v> next; node(int hash, k key, v value, node<k,v> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } // ...}
public class hashmap<k,v> extends abstractmap<k,v> implements map<k,v>, cloneable, rializable {/** * 序列号版本号 */ private static final long rialversionuid = 362498820763181265l; /** * 初始化容量,为16=2的4次幂 */ static final int default_initial_capacity = 1 << 4; // aka 16 /** * 最大容量,为2的30次幂 */ static final int maximum_capacity = 1 << 30; /** * 默认的负载因子,默认值是0.75 */ static f火烧圆明园资料inal float default_load_factor = 0.75f; /** * 链表节点树超过8就转为为红黑树 */ static final int treeify_threshold = 8; /** * 红黑树节点少于6就再转换回链表 */ static final int untreeify_threshold = 6; /** * 桶中结构转化为红黑树对应的数组长度最小的值 */ static final int min_treeify_capacity = 64艾薇儿什么歌好听; // ... /** * hashmap存储元素的数组 */transient node<k,v>[] table; /** * 用来存放缓存 */ transient t<map.entry<k,v>> entryt; /** * hashmap存放元素的个数 */ transient int size; /** * 用来记录hashmap的修改次数 */ transient int modcount; /** * 用来调整大小下一个容量的值(容量*负载因子) */ int threshold; /** * hash表的负载因子 */ final float loadfactor;}
public hashmap(int initialcapacity, float loadfactor) { // 初始容量不能小于0,小于0直接抛出illegalargumentexception if (initialcapacity < 0) throw new illegalargumentexception("illegal initial capacity: " + initialcapacity); // 初始容量大于最大容量的时候,取最大容量作为初始容量 if (initialcapacity > maximum_capacity) initialcapacity = maximum_capacity; // 负载因子不能小于0,而且要是数值类型,isnan:true,表示就是非数值类型 if (loadfactor <= 0 || float.isnan(loadfactor)) throw new illegalargumentexception("illegal load factor: " + loadfactor); // 将指定的失恋33天 小说负载因子赋值给全局变量 this.loadfactor = loadfactor; // threshold = (容量) * (负载因子) this.threshold = tablesizefor(initialcapacity);}public hashmap(int initialcapacity) { // 初始化容量和默认负载因子 this(initialcapacity, default_load_factor);}public hashmap() { // 默认的负载因子为0.75this.loadfactor = default_load_factor;}
然后,我们知道hashmap的默认容量是16,然后是在哪里赋值的?从上面这个代码就可以知道this.threshold = tablesizefor(initialcapacity);
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;}
这里涉及到计算机基本知识的,右移运算和或运算,下面给出图例:通过比较麻烦的计算得出n为16
往代码里翻,还找到下面这个构造方法public hashmap(map<? extends k, ? extends v> m):这个构造方法是用于构造一个映射关系与指定 map 相同的新 hashmap:
public hashmap(map<? extends k, ? extends v> m) { this.loadfactor = default_load_factor; putmapentries(m, fal); }
看一下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 未初始化的情况 // 加上1.0f的目的是对小数向上取整,保证最大容量,减少resize的调用次数 float ft = ((float)s / loadfactor) + 1.0f; int t = ((ft < (float)maximum_capacity) ? (int)ft : maximum_capacity); // 计算出来的t大于hashmap的阀值,进行tablesizefor if (t > threshold) threshold = tablesizefor(t); } el if (s > threshold) // 已经初始化的情况,进行扩容resize resize(); // 遍历,将map中的所有元素都添加到hashmap中 for (map.entry<? extends k, ? extends v> e : m.entryt()) { k key = e.getkey(); v value = e.getvalue(); putval(hash(key), key, value, fal, evict); } }}
在hashmap的java.util.hashmap#hash,这个方法中有特定的用于计算哈希值的方法:这个方法的作用?这个方法就是用于hashmap当put对应的key之后,计算特定的hashcode,然后再(n-1)&hash计算对应的数组table的下标,这个后面跟一下hashmap源码才比较清楚:
static final int hash(object key) { int h; return (key == null) ? 0 : (h = key.hashcode()) ^ (h >>> 16);}
看起来代码只有两行,然后其实蕴含了一种散列算法的思想,下面简单分析一下:这里先将代码进行拆分,看起来清晰点:
static final int hash(object key) { // 传入的key为null,返回默认值0 if (key == null) return 0; // 计算哈希code int h = key.hashcode(); // 将计算出来的hashcode右移16位,相当于乘于(1/2)的16次方 int t = h >>> 16; // 将两个值做异或运算然后返回 return h ^ t;}
其实里面要做的事情是先计算出hashcode,然后将hashcode右移16位,然后这两个数再做异或运算。看起来是这么一回事,然后作者的意图是什么?首先既然是散列算法,散列算法的目的就是为了让数据均匀分布
从图可以看出,使用异或运算,出现0和1的概率是相等的,所以这就是为什么要使用异或运算的原因,散列算法的本质目的就是为了让数据均匀分布,使用异或运算得出的哈希值因为比较均匀散列分布,所以出现哈希冲突的概率就小很多
补充:
与运算:两个数相应的位数字都是1,与运算后是1,其余情况是0;或运算:两个数相应的位数字只要有1个是1,或运算后是1,否则是0;异或运算:两个数相应的位数字相同,结果是0,否则是1;
然后为什么再进行右移16位?我们知道,int类型最大的数值是2的32次方,然后可以分为高16位加上低16位,右移16位就是使数值变小了,“左大右小”,这个是位移运算的准则
哈希冲突也可以称之为哈希碰撞,理论上的哈希冲突是指计算出来的哈希值一样,导致冲突了,不过在hashmap中的哈希冲突具体是指(n-1)&hash,这个值是hashmap里数组的下标。jdk8之前的处理方法是通过链表处理,只要hash冲突了,就会将节点添加到链表尾部;jdk8之后的做法是通过链表+红黑树的方法,最开始哈希冲突了,也是用链表,然后链表节点达到8个,数组长度超过64的情况,转成红黑树,这个可以在源码里找到答案
翻下源码,hashmap#putval,里面的逻辑,先校验计算出来的,数组tab的下标,i=(n-1)&hash是否冲突了,不冲突就新增节点,冲突的情况,转链表或者红黑树
if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newnode(hash, key, value, null);
上面是核心的流程,忽略了存在重复的键,则为该键替换新值 value, size 大于阈值 threshold,则进行扩容等等这些情况
ok,还是跟一下put源码:
public v put(k key, v value) { return putval(hash(key), key, value, fal, true);}final v putval(int hash, k key, v value, boolean onlyifabnt, boolean evict) { node<k,v>[] tab; node<k,v> p; int n, i; // 第1次新增,初始数据resize if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 判断是否出现hash冲突 if ((p = tab[i = (n - 1) & hash]) == null) // hash不冲突,新增节点 tab[i] = newnode(hash, key, value, null); el { // 哈希冲突的情况,使用链表或者红黑树处理 node<k,v> e; k k; // 存在重复的键的情况,key和hash都相等 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) // 将旧的节点对象赋值给新的e e = p; el if (p instanceof treenode) // 使用了红黑树节点 // 将节点放到红黑树中 e = ((treenode<k,v>)p).puttreeval(this, tab, hash, key, value); el { // 链表的情况 // 无限循环 for (int bincount = 0; ; ++bincount) { // 一直遍历,找到尾节点 if ((e = p.next) == null) { // 将新节点添加到尾部 p.next = newnode(hash, key, value, null); // 节点数量大于8,转为红黑树 if (bincount >= treeify_threshold - 1) // -1 for 1st treeifybin(tab, hash); // 跳出循环 break; } // 也是为了避免hashcode和key一样的情况 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; // 重新赋值,用于链表的遍历 p = e; } } // 桶中找到的key、hash相等的情况,也就是找到了重复的键,要使用新值替换旧值 if (e != null) { // existing mapping for key // 记录e的值 v oldvalue = e.value; if (!onlyifabnt || oldvalue == null) // 用新值替换旧值 e.value = value; // 访问后回调 afternodeaccess(e); // 返回旧值 return oldvalue; } } // 记录修改次数 ++modcount; // size大于threshole,进行扩容 if (++size > threshold) resize(); // 回调方法 afternodeinrtion(evict); return null;}
然后是怎么转换为红黑树的?红黑树的知识相对比较复杂
final void treeifybin(node<k,v>[] tab, int hash) { int n, index; node<k,v> e; // min_treeify_capacity值为64,也就是说数组长度小于64是不会真正转红黑树的 if (tab == null || (n = tab.length) < min_treeify_capacity) // 扩容方法 resize(); // 转红黑树操作 el if ((e = tab[index = (n - 1) & hash]) != null) { // 红黑树的头节点hd和尾节点t1 treenode<k,v> hd = null, tl = null; do { // 构建树节点 treenode<k,v> p = replacementtreenode(e, null); if (tl == null) // 新节点p赋值给红黑树的头节点 hd = p; el { // 新节点的前节点就是原来的尾节点t1 p.prev = tl; // 尾部节点t1的next节点就是新节点 tl.next = p; } tl = p; } while ((e = e.next) != null); // 让数组的节点执行新建的树节点,之后这个节点就变成treenode if ((tab[index] = hd) != null) hd.treeify(tab); }}
这个知识点是hashmap中的一个重点之一,也是一个比较难的问题
当hashmap中元素个数超过threshold,threshold为数组长度乘以负载因子loadfactor,loadfactor默认是0.75f
resize这个方法是hashmap的扩容方法,是比较耗时的。hashmap在扩容时,都是翻两倍,比如16的容量扩大到32,。hashmap进行扩容的方法是比较巧妙的,扩容后,与原来的下标(n-1)&hash相对,其实只是多了1bit位。扩容后节点要么是在原来位置,听起来好像很懵,所以还是认真看下面的分析:
下面给出例子,比如从容量为16扩容到32时,画图表示:
进行扩容,扩大到原来的两倍:
到这一步,下标(n-1) & hash,扩容后的数据10101和原来的00101相比,其实就是多了1bit,10101是十进制的21,而21=5+16,就是“原位置+旧容量”,还有另外一种情况是保持为0的情况,这种情况是不改变位置的
下面给出一份表格,数据如图:
容量为16的情况
有低位的两个指针lohead、llotail,高位的两个指针hihead、hitail
扩容到32之后,再两个链表加到对应位置。分别有两种情况,保持原来位置的和“原位置+旧容量”这个位置
所以,扩容的过程,对应的节点位置改变是这样的过程:
经过上面比较详细的分析,这个实现逻辑是可以在代码里找到对应的,ok,跟一下对应的源码:
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) { // 超过最大容量 即 1 <<< 30 // 超过最大容量就不扩充了,修改阀值为最大容量 threshold = integer.max_value; return oldtab; } // 没超过的情况,扩大为原来的两倍 el if ((newcap = oldcap << 1) < maximum_capacity && oldcap >= default_initial_capacity) newthr = oldthr << 1; // double threshold } el if (oldthr > 0) // initial capacity was placed in threshold // 老阀值赋值给新的数组长度 newcap = oldthr; el { // zero initial threshold signifies using defaults // 使用默认值16 newcap = default_initial_capacity; newthr = (int)(default_load_factor * default_initial_capacity); } // 重新计算阀值,然后要赋值给threshold if (newthr == 0) { float ft = (float)newcap * loadfactor; newthr = (newcap < maximum_capacity && ft < (float)maximum_capacity ? (int)ft : integer.max_value); } // 新的阀值,原来默认是12,现在变为24 threshold = newthr; // 创建新的节点, newcap是新的数组长度,为32 @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; el if (e instanceof treenode) // 是红黑树节点,调用split方法 ((treenode<k,v>)e).split(this, newtab, j, oldcap); el { // prerve 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; el lotail.next = e; lotail = e; } el { // 需要移动位置 ,调整到“原位置+旧容量”这个位置 if (hitail == null) hihead = e; el // hitail指向要移动的节点e hitail.next = e; hitail = e; } } while ((e = next) != null); if (lotail != null) { lotail.next = null; // 位置不变 newtab[j] = lohead; } if (hitail != null) { // hitail指向null hitail.next = null; // oldcap是旧容量 ,移动到“原位置+旧容量”这个位置 newtab[j + oldcap] = hihead; } } } } } return newtab;}
remove方法,这里思路是先要找到元素的位置,如果是链表,遍历链表remove元素就可以,红黑树的情况就遍历红黑树找到节点,然后remove树节点,如果这时候树节点数小于6,这种情况就要转链表
@overridepublic 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; // 数组下标是(n-1)&hash,能找得到元素的情况 if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { node<k,v> node = null, e; k k; v v; // 桶上的节点就是要找的key if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) // 将node指向该节点 node = p; el if ((e = p.next) != null) { // 链表或者是红黑树节点的情况 if (p instanceof treenode) // 找到红黑树节点 node = ((treenode<k,v>)p).gettreenode(hash, key); el { // 链表的情况 // 遍历链表,找到需要找的节点 do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; } p = e; } while ((e = e.next) != null); } } // 找到节点之后 if (node != null && (!matchvalue || (v = node.value) == value || (value != null && value.equals(v)))) { if (node instanceof treenode) // 红黑树remove节点 ((treenode<k,v>)node).removetreenode(this, tab, movable); el if (node == p) // 链表remove,通过改变指针 tab[index] = node.next; el p.next = node.next; // 记录修改次数 ++modcount; // 变动的数量 --size; afternoderemoval(node); return node; } } return null;}
get方法:通过key找到value,这个方法比较容易理解
public v get(object key) { node<k,v> e; return (e = getnode(hash(key), key)) == null ? null : e.value;}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) { // 不是第1个节点的情况,那就有可能是链表或者红黑树节点 if (first instanceof treenode) // 根据gettreenode获取红黑树节点 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;}
本文发布于:2023-04-05 05:04:33,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/ebbd9d1a6e7a498feeb33dfa1b3f8f93.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:hashmap源码扩容(hashmap底层原理面试).doc
本文 PDF 下载地址:hashmap源码扩容(hashmap底层原理面试).pdf
留言与评论(共有 0 条评论) |