首页 > 编程知识 正文

Java8 HashMap 扩容之后旧元素存放位置

时间:2023-05-06 01:20:20 阅读:30259 作者:3142

java8 HashMap扩展后的旧元素的存储位置从源代码中可以看到,Java在扩展时创建新的NodeK,V[]以存储扩展后的值,并清空旧的Node数组;

至于旧值移动到新节点时存储在哪个节点上,Java由(e.hash oldCap )==0确定。

在为0的情况下,将该节点配置为新数组时的索引位置与旧数组时的索引位置相等,标记为下级区域的链表lo的开头-low;

不为0的情况下,将该节点配置到新数组时的索引位置等于旧数组时的索引位置加上旧数组的长度,标记为上级链表hi的开头high。

举例说明:

如果e.key=7且旧数组oldCap的长度为16 :根据? 0:(h=key.hashcode () ) ) ) ) ) ) ) ); 并且,在key为int时key.hashCode返回是因为key自身能够计算出e.hash=7是因为oldCap=16,此时,如果[e.hasholdcap]=0,则e.hash的线条7 16=11110000=0,因此值为7的节点放置在新数组中时的索引位置与放置在旧数组中时的索引位置相同。 e.key=17,旧数组oldCap的长度为16时:同样可以计算出17 16=10001 10000=10000,因此值为17的节点等于旧数组的索引位置加上旧数组的长度; 带hashmap扩展源代码

final NodeK,V[] resize (),V[] oldTab=table; intoldcap=(oldtab==null )? 0 : oldTab.length; int oldThr=threshold; int newCap,newThr=0; if(oldcap0) if ) oldcap=maximum_capacity ) { threshold=Integer.MAX_VALUE; 返回操作数据库; }elseif((newcap=oldcap1) maximum _ capacityoldcap=default _ initial _ capacity ) newThr=oldThr 1; //double threshold } else if (old thr0)//initialcapacitywasplacedinthresholdnewcap=old thr; else {//zeroinitialthresholdsignifiesusingdefaultsnewcap=default _ initial _ capacity; Newthr=(int ) ) default _ load _ factor * default _ initial _ capacity ); (if ) Newthr==0) floatft=) float ) newCap * loadFactor; newthr=(newcapmaximum_capacity ft ) float ) maximum _ capacity? (int ) ft : Integer.MAX_VALUE; } threshold=newThr; @suppresswarnings((rawtypes )、(unchecked'} ) ) NodeK,v ) ) new tab=(nodek,v ) ) newnode ) newcap ); table=newTab; if(oldtab!=null(for ) intj=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; elseif(einstanceoftreenode ) (TreeNodeK,v ) e ).split (this,newTab,j,oldCap ); else { //preserve order NodeK,V loHead=null,loTail=null; NodeK,V hiHead=null,hiTail=null; NodeK,V next; do { next=e.next; if(e.hasholdcap )==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; } } } }返回新tab; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。