Java源码解析HashMap简介
本文基于jdk1.8进行分析
HashMap是java开发中可以说必然会用到的一个集合。本文就HashMap的源码实现进行分析。
首先看一下源码中类的javadoc注释对HashMap的解释。如下图。HashMap是对Map接口的基于hash表的实现。这个实现提供了map的所有可选操作,并且允许null值(可以多个)和一个null的key(仅限一个)。HashMap和HashTable十分相似,除了HashMap是非同步的且允许null元素。这个类不保证map里的顺序,更进一步,随着时间的推移,它甚至不保证顺序一直不变。
这个实现为get和put这样的基本操作提供常量级性能,它假设hash函数把元素们比较好的分散到各个桶里。用迭代器遍历集合需要的时间,和HashMap的容量与HashMap里的Entry数量的和成正比。所以,如果遍历性能很重要的话,一定不要把初始容量设置的太大,或者把负载因子设置的太小。
一个hashmap有两个影响它的性能的参数,初始容量和负载因子。容量是哈希表中桶的数量,初始容量就是创建哈希表时桶的数量。负载银子是哈希表的容量自动扩容前哈希表能够达到多满。当哈希表中条目的数量超过当前容量和负载因子的乘积后,哈希表会进行重新哈希(也就是,内部数据结构重建),以使哈希表大约拥有2倍数量的桶。
作为一个通常的规则,默认负载银子(0.75)提供了一个时间和空间的比较好的平衡。更高的负载因子会降低空间消耗但是会增加查找的消耗。当设置初始容量时,哈希表中期望的条目数量和它的负载因子应该考虑在内,以尽可能的减小重新哈希的次数。如果初始容量比条目最大数量除以负载因子还大,那么重新哈希操作就不会发生。
如果许多entry需要存储在哈希表中,用能够容纳entry的足够大的容量来创建哈希表,比让它在需要的时候自动扩容更有效率。请注意,使用多个hash值相等的key肯定会降低任何哈希表的效率。
请注意这个实现不是同步的。如果多个线程同时访问哈希表,并且至少有一个线程会修改哈希表的结构,那么哈希表外部必须进行同步。
/** *HashtablebasedimplementationoftheMapinterface.This *implementationprovidesalloftheoptionalmapoperations,andpermits *nullvaluesandthenullkey.(TheHashMap *classisroughlyequivalenttoHashtable,exceptthatitis *unsynchronizedandpermitsnulls.)Thisclassmakesnoguaranteesasto *theorderofthemap;inparticular,itdoesnotguaranteethattheorder *willremainconstantovertime. *Thisimplementationprovidesconstant-timeperformanceforthebasic *operations(getandput),assumingthehashfunction *dispersestheelementsproperlyamongthebuckets.Iterationover *collectionviewsrequirestimeproportionaltothe"capacity"ofthe *HashMapinstance(thenumberofbuckets)plusitssize(thenumber *ofkey-valuemappings).Thus,it'sveryimportantnottosettheinitial *capacitytoohigh(ortheloadfactortoolow)ifiterationperformanceis *important. *
AninstanceofHashMaphastwoparametersthataffectits *performance:initialcapacityandloadfactor.The *capacityisthenumberofbucketsinthehashtable,andtheinitial *capacityissimplythecapacityatthetimethehashtableiscreated.The *loadfactorisameasureofhowfullthehashtableisallowedto *getbeforeitscapacityisautomaticallyincreased.Whenthenumberof *entriesinthehashtableexceedstheproductoftheloadfactorandthe *currentcapacity,thehashtableisrehashed(thatis,internaldata *structuresarerebuilt)sothatthehashtablehasapproximatelytwicethe *numberofbuckets. *
Asageneralrule,thedefaultloadfactor(.75)offersagood *tradeoffbetweentimeandspacecosts.Highervaluesdecreasethe *spaceoverheadbutincreasethelookupcost(reflectedinmostof *theoperationsoftheHashMapclass,including *getandput).Theexpectednumberofentriesin *themapanditsloadfactorshouldbetakenintoaccountwhen *settingitsinitialcapacity,soastominimizethenumberof *rehashoperations.Iftheinitialcapacityisgreaterthanthe *maximumnumberofentriesdividedbytheloadfactor,norehash *operationswilleveroccur. *
IfmanymappingsaretobestoredinaHashMap *instance,creatingitwithasufficientlylargecapacitywillallow *themappingstobestoredmoreefficientlythanlettingitperform *automaticrehashingasneededtogrowthetable.Notethatusing *manykeyswiththesame{@codehashCode()}isasurewaytoslow *downperformanceofanyhashtable.Toameliorateimpact,whenkeys *are{@linkComparable},thisclassmayusecomparisonorderamong *keystohelpbreakties. *
Notethatthisimplementationisnotsynchronized. *Ifmultiplethreadsaccessahashmapconcurrently,andatleastoneof *thethreadsmodifiesthemapstructurally,itmustbe *synchronizedexternally.(Astructuralmodificationisanyoperation *thataddsordeletesoneormoremappings;merelychangingthevalue *associatedwithakeythataninstancealreadycontainsisnota *structuralmodification.)Thisistypicallyaccomplishedby *synchronizingonsomeobjectthatnaturallyencapsulatesthemap. *Ifnosuchobjectexists,themapshouldbe"wrapped"usingthe *{@linkCollections#synchronizedMapCollections.synchronizedMap} *method.Thisisbestdoneatcreationtime,topreventaccidental *unsynchronizedaccesstothemap:
*Mapm=Collections.synchronizedMap(newHashMap(...));*Theiteratorsreturnedbyallofthisclass's"collectionviewmethods" *arefail-fast:ifthemapisstructurallymodifiedatanytimeafter *theiteratoriscreated,inanywayexceptthroughtheiterator'sown *removemethod,theiteratorwillthrowa *{@linkConcurrentModificationException}.Thus,inthefaceofconcurrent *modification,theiteratorfailsquicklyandcleanly,ratherthanrisking *arbitrary,non-deterministicbehavioratanundeterminedtimeinthe *future. *
Notethatthefail-fastbehaviorofaniteratorcannotbeguaranteed *asitis,generallyspeaking,impossibletomakeanyhardguaranteesinthe *presenceofunsynchronizedconcurrentmodification.Fail-fastiterators *throwConcurrentModificationExceptiononabest-effortbasis. *Therefore,itwouldbewrongtowriteaprogramthatdependedonthis *exceptionforitscorrectness:thefail-fastbehaviorofiterators *shouldbeusedonlytodetectbugs. *
Thisclassisamemberofthe *
*JavaCollectionsFramework. *@param thetypeofkeysmaintainedbythismap *@param thetypeofmappedvalues *@authorDougLea *@authorJoshBloch *@authorArthurvanHoff *@authorNealGafter *@seeObject#hashCode() *@seeCollection *@seeMap *@seeTreeMap *@seeHashtable *@since1.2 **/
Thisistheend。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接