Recently friends to interview was asked some HashMap related questions, HashMap initial capacity Ah, what operation is the most time-consuming, and so on, before seen HashMap source, just here also in summary.
Mainly around the following points:
- HashMap is implemented by array + linked list (Jdk8 upgrade to red-black tree) structure
- HashMap allocates memory when first put (ArrayList is also at the first add)
- HashMap default array size is 16
- HashMap size is a multiple of 2 after each expansion
- HashMap expands when the capacity threshold (Threshold=capacity*loadfactor) is reached
- HashMap How to do the expansion
Code reference jdk1.7
HashMap is implemented by array + linked list (Jdk8 upgrade to red-black tree) structure
This is the time when the put will initialize an array, when the key hash conflict when the same bucket added new value
Initializing an array
Privatevoid inflatetable (int tosize) { int capacity = ROUNDUPTOPOWEROF2 (tosize); = (int) math.min (capacity * Loadfactor, maximum_capacity + 1); New entry[capacity]; Inithashseedasneeded (capacity); }
Publicv put (K key, V value) {if(Table = =empty_table) {inflatetable (threshold); } //key is null when directly put if(Key = =NULL) returnPutfornullkey (value); inthash =hash (key); inti =indexfor (hash, table.length); for(entry<k,v> e = table[i]; E! =NULL; E =e.next) {Object k; //value substitution when hash value is equal to &&key equals if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) {V OldValue=E.value; E.value=value; E.recordaccess ( This); returnOldValue; } } //Otherwise, add a new valuemodcount++; AddEntry (hash, key, value, I); return NULL; }
HashMap allocates memory when first put (ArrayList is also at the first add)
PublicHashMap (intInitialcapacity,floatloadfactor) { if(Initialcapacity < 0) Throw NewIllegalArgumentException ("Illegal initial capacity:" +initialcapacity); if(Initialcapacity >maximum_capacity) initialcapacity=maximum_capacity; if(loadfactor <= 0 | |Float.isnan (loadfactor))Throw NewIllegalArgumentException ("Illegal load factor:" +loadfactor); This. Loadfactor =Loadfactor; Threshold=initialcapacity; Init (); }
This is the constructor of HashMap, see here just initialized the Loadfactor and threshold these two parameters, and in the previous analysis, the first time the put element will execute the Inflatetable function to initialize the array:
Table = new entry[capacity]; memory allocation
HashMap default array size is 16
static final int default_initial_capacity = 1 << 4; aka 16
HashMap size is a multiple of 2 after each expansion
void addentry (intint bucketindex) { if (size >= threshold) & & (null ! = Table[bucketindex])) { Resize (2 * table.length) ; = (null ! = key)? Hash (key): 0; = Indexfor (hash, table.length); } Createentry (hash, key, value, Bucketindex); }
When calling AddEntry to add a new element, it will determine if the size reaches a critical value, and if it does, the resize method can see that the new capacity is the original capacity
HashMap How to do the expansion
static int indexfor (int h, int length) { //Assert integer.bitcount (length) = = 1: "Length must be a non-zero power of 2 "; Return H & (length-1); }
This code is for the array subscript calculation
The resize code is as follows
JKD1.7
voidResizeintnewcapacity) {entry[] oldtable=table; intOldcapacity =oldtable.length; if(Oldcapacity = =maximum_capacity) {Threshold=Integer.max_value; return; } entry[] NewTable=NewEntry[newcapacity]; Transfer (newtable, inithashseedasneeded (newcapacity)); Table=newtable; Threshold= (int) math.min (newcapacity * loadfactor, maximum_capacity + 1); } /*** Transfers all entries from the current table to newtable. */ voidTransfer (entry[] newtable,Booleanrehash) { intNewcapacity =newtable.length; for(entry<k,v>e:table) { while(NULL!=e) {Entry<K,V> next =E.next; if(Rehash) {E.hash=NULL= = E.key? 0: Hash (E.key); } inti =indexfor (E.hash, newcapacity); E.next=Newtable[i]; Newtable[i]=e; E=Next; } } }
JDK1.8 here will involve hashmap a very ingenious point. Since table.length-capacity is definitely 2 of the N-square, using the & bit operation means that only the most high-level, so that the index is not recalculated, the element is either in the original position, or in the original position + oldcapacity
If the increased high is 0,resize, the index does not change:
If the increased high is 1,resize after index increases OLDCAP,:
The trick of this design is to save a part of the time to recalculate the hash, while the new one is 0 or 1 probability can be considered equal, so in the process of resize the original collision of the node and evenly distributed to two buckets.
Do{Next=E.next; if((E.hash & oldcap) = = 0) { if(Lotail = =NULL) Lohead=e; ElseLotail.next=e; Lotail=e; } Else { if(Hitail = =NULL) Hihead=e; ElseHitail.next=e; Hitail=e; } } while((e = next)! =NULL);
Some analysis records of Java HashMap