ArrayList及HashMap的扩容规则讲解
1、ArrayList
默认大小为10
/** *Defaultinitialcapacity. */ privatestaticfinalintDEFAULT_CAPACITY=10;
最大容量为2^30-8
/** *Themaximumsizeofarraytoallocate. *SomeVMsreservesomeheaderwordsinanarray. *Attemptstoallocatelargerarraysmayresultin *OutOfMemoryError:RequestedarraysizeexceedsVMlimit */ privatestaticfinalintMAX_ARRAY_SIZE=Integer.MAX_VALUE-8; /** *Aconstantholdingthemaximumvaluean{@codeint}can *have,231-1. */ publicstaticfinalintMAX_VALUE=0x7fffffff;
扩容规则为:oldCapacity*1.5
/** *Increasesthecapacitytoensurethatitcanholdatleastthe *numberofelementsspecifiedbytheminimumcapacityargument. *@paramminCapacitythedesiredminimumcapacity */ privatevoidgrow(intminCapacity){ //overflow-consciouscode intoldCapacity=elementData.length; intnewCapacity=oldCapacity+(oldCapacity>>1); if(newCapacity-minCapacity<0) newCapacity=minCapacity; if(newCapacity-MAX_ARRAY_SIZE>0) newCapacity=hugeCapacity(minCapacity); //minCapacityisusuallyclosetosize,sothisisawin: elementData=Arrays.copyOf(elementData,newCapacity); }
2、HashMap
默认大小:16
/** *Thedefaultinitialcapacity-MUSTbeapoweroftwo. */ staticfinalintDEFAULT_INITIAL_CAPACITY=1<<4;//aka16
最大容量为:2^30
/** *Themaximumcapacity,usedifahighervalueisimplicitlyspecified *byeitheroftheconstructorswitharguments. *MUSTbeapoweroftwo<=1<<30. */ staticfinalintMAXIMUM_CAPACITY=1<<30;
扩容规则为:大于oldCapacity的最小的2的n次方整数
/** *Addsanewentrywiththespecifiedkey,valueandhashcodeto *thespecifiedbucket.Itistheresponsibilityofthis *methodtoresizethetableifappropriate. *Subclassoverridesthistoalterthebehaviorofputmethod. */ voidaddEntry(inthash,Kkey,Vvalue,intbucketIndex){ if((size>=threshold)&&(null!=table[bucketIndex])){ resize(2*table.length); hash=(null!=key)?hash(key):0; bucketIndex=indexFor(hash,table.length); } createEntry(hash,key,value,bucketIndex); }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接