JAVA HASHMAP Parsing

Source: Internet
Author: User

1. Introduction (in fact, hashmap annotation of the general translation)

This article is based on JDK1.8, there are some differences with the HashMap in JDK1.7, crossing attention to differences.

The HASHMAP implements the map interface and provides efficient key-value access. HashMap is very similar to Hashtable, except that HashMap allows key and value to be null, and hashmap non-thread-safe, while Hashtabel is thread-safe. HashMap does not guarantee the order in which key-value pairs are inserted, nor does it guarantee that the order of key-value pairs remains the same after constant insertions and deletions (guaranteed linkedhashmap in order).

If the elements in the hashmap are evenly distributed across buckets, the put and get operations can be approached with constant-level time consumption. The time required to iterate on the HashMap is affected by the capacity, so do not set the initialization capacity too large or the load factor is too small when initializing.

Typically, the default load factor, 0.75, makes a good tradeoff between time consumption and space consumption. Setting a larger load factor can improve space utilization, but it also increases the consumption of query time.

If there are many elements that will exist in HashMap, set a relatively large value at creation time to avoid automatic expansion and rehashing, which can improve efficiency. If many keys have the same hashcode () value, the performance of the HashMap is reduced.

Note that HashMap is not thread-safe, and if you want to use a thread-safe map, you can replace him with Collections.synchronizedmap, HashTable, and Concurrnethashmap.

The iterator (iterator) returned by HashMap is a fast-failing (fail-fast). If another thread modifies HashMap (put,remove) during the iteration, a concurrentmodificationexception is thrown, but the Remove method using the iterator itself does not.

2.HASHMAP internal data structures and member variables

The HASHMAP member variable has the following (excluding class variables):

transient Node<k,v>[] table; transient Set<map.entry<k,v>> EntrySet; transient int size; transient int Modcount; int threshold; Final float loadfactor;

The table variable is where the element is actually stored, an array of internal data structure node.

EntrySet actually does not save the element internally, and is not actually instantiated until after the call to EntrySet (), otherwise it is always null. Because HashMap does not implement an iterator interface, the table variable is not simply an array, it actually becomes the structure of the array + local linked list or array + local red-black tree. The usual traversal of hashmap, usually calls the EntrySet () method, gets the EntrySet variable, and then iterates through it.

The size variable holds the number of elements that are currently inserted, not the length of the table.

Modecount is used to implement a fast failure mechanism. When traversing through EntrySet (EntrySet (). iterator (), either directly using an iterator or using a foreach loop, it is quite the same as calling the method), and each time a new iterator variable is created that holds the modcount in the state at that time , when calling HashMap's put, remove, and so on, the modecount increments, traversing the next element (next ()), checking if the modecount at this time is the same as the Modecount saved when the iteration was created, or throws an exception.

Threhold is a capacity * load factor that triggers expansion and rehashing operations when size exceeds this value.

Loadfactor is the load factor, which determines when the hashmap reaches "more than full" is the expansion operation.

HashMap's internal data structures are:

 Static classNode<k,v>ImplementsMap.entry<k,v> {        Final intHash; FinalK Key;        V value; Node<K,V>Next;} Static Final classTreenode<k,v>extendsLinkedhashmap.entry<k,v>{TreeNode<K,V> parent;//Red-black Tree LinksTreenode<k,v>Left ; TreeNode<K,V>Right ; TreeNode<K,V> prev;//needed to unlink next upon deletion        BooleanRed;}

Here are just two of the other EntrySet classes, the values of the value method, the classes returned by the keys method, and their corresponding iterators, which are not described here.

The node class, which is the class of the instance saved in the table above, has a hash-not equal to the value of hashcode (), but is closely related to the hashcode () value, and the same hashcode () corresponds to the same hash value; key is the key. The saved Value;value is saved by key, and next points to the next node, which provides a solution when the element is in conflict. As you can see, in fact HashMap not only save value, but also save some necessary information ( nonsense!). ).

TreeNode is a subclass of node (Linkedhashmap.entry inherits from node). When a bucket in the hashmap conflict too much, this position of the linked list will become very long, reduce the efficiency of the query, this time need to convert the list into a tree, node node will be converted to TreeNode as a sub-nodes, improve the efficiency of the query (why not start with the tree structure, Maintain tree structure don't time! ), the number of collisions is reduced to a certain amount (remove), the tree is degraded to a list, and TreeNode is converted to node.

3.HASHMAP Logical Storage structure

Figure one (the mouse moves to the top of the graph to see the corresponding title) shows the table structure without conflict.

Figure II shows the table structure with a certain amount of conflict in a bucket position.

Figure III shows a large number of conflicts in a bucket position, from a linked list to a tree structure.

(The so-called bucket is one of the positions of the table array, and the blue in three images indicates that there is already a non-null node)

4.HASHMAP Implementation principle

The key methods of external exposure of HashMap are discussed from several key internal method entrances.

4.1 Calculating Table Size

Calculates the length of the table in HashMap when it should be initialized or enlarged. The table length in the HashMap is a power of 2, why do you want to ensure that the elements can be evenly distributed on the table, why can guarantee, after-school homework ~

The result of the execution of the code is to obtain a power exponent of a minimum of 2 greater than or equal to the cap. The algorithm is very ingenious and is analyzed as follows:

First, the CAP's value range is,>=0; so n >=-1;

When n = 0 o'clock, before the return statement, the value of n is 0, and the result is returned at 1;

When n =-1, the highest bit should always be 1 (do not understand the revision of the complement), so it is a negative number, the final result is 1;

When n > 0 o'clock, any integer binary can be represented as 001XXXXX (explanation, here is 1 is the highest level of 1, the preamble is all 0, and here the leading 0 number is not necessarily 2, simplifying some, the following calculation is convenient, followed by x, may be 1, may be 0, In fact, we don't care, but the whole binary string is 32 in length.

First Operation: n | = n >>> 1, i.e.:

001XXXXX |

0001XXXX =

0011XXXXX; Now we can guarantee that there will be at least 2 consecutive 1 after the preamble 0 (or at this time, except for the leading 0, all 1, not repeat);

Second operation: n |= n>>>2, i.e.:

0011XXXXX |

000011XXX =

001111XXXX; Now we can guarantee that there will be at least 4 consecutive 1 after the preamble 0.

And so on, finally we can get a number, except for the leading 0, all 1.

N+1 is the power of a 2, and is greater than or equal to the cap of the smallest 2 of the power of the number.

Why would cap-1 be here first? Because it is to prevent the cap is already 2 of the power of the number, you can try the above algorithm, if not cap-1, then the resulting tree will be twice times the cap, but obviously not necessary, we want the cap.

 /*** Returns A power of the size for the given target capacity. */    Static Final intTablesizefor (intcap) {        intn = 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; }

4.2 Hash algorithm

Compared to the 1.7 hash algorithm, 1.8 is a lot simpler. Not directly using Hashcode () as the hash value, is to avoid less conflict, (can refer to other posts), compared to the 1.7 calculation method, significantly simplified a lot. The official argument is that this is a comprehensive consideration of practicality and efficiency. (That is, it has been able to guarantee a lower collision rate in most cases, and the calculation method is relatively simple and efficient, by contrast, the collision means that different keys are assigned to the same bucket, which has to evolve into the form of a linked table or tree).

The specific algorithm is that key = = NULL returns 0, otherwise equal to Key.hashcode () or key.hashcode () unsigned right shift 16 bits.

Static Final int Hash (Object key) {        int  h;
This also indirectly proves that key can be null
returnnull)? 0: (H = key.hashcode ()) ^ (h >>>); }
4.3 Calculate the bucket bit (where to place the table array)

1.8 did not separate him into a method, from the Putval () method to intercept a paragraph. n is the length of the table, and the hash is the value that key is calculated by the hash algorithm above. Some people may think that the length of the table is a power of 2 to be able to quickly calculate subscripts (using the & operator), and the computed subscript will not exceed the table length. In fact, the power of table 2 is to minimize the probability of collisions, and for any integer n, the subscript can be computed using (n-1) & length, and the calculated result is less than N.

(n-1) & Hash

4.4 Put method (Inserts an Element)

1.8, is called directly

Final V putval (intboolean  onlyifabsent,                   boolean evict)
The first parameter is the value computed by the hash method we wrote in the previous second, and the last two Boolean arguments are all false at this time.

Understand this method directly by referencing the source code and annotations.

Putval Source code and comments

4.5 Resize expansion

Expansion operations, not only need to enlarge the length of the table, the location of node will also change (in fact, if the length of the original table is N,node subscript is T, then in the new table, a node in the subscript is either T, or t+n, no other choice). Why?

1. The original table has a length of 001000000;

2. The new table length is 010000000;

3. In old table subscript t = 000111111 & hash = 000XXXXX (x may be 1 or 0)

4. In the new table subscript t = 0011111 & hash = 00MXXXXX, compared to T, except that M may be 1 maybe 0, each x in T and X in T are the same (think why, should be all hash & 11111 Well, definitely The same! )

5. If m = 0, then t = 000XXXXX = t; if m = 1, then t = 001XXXX = t + 0010000 = t + oldcap = t + the length of the original table

6. So under what circumstances will M be 0? Under what circumstances is M or 1? Obviously, when the hash = xx0xxxx, M = 0, which means hash & (newCap-1) = xx0xxxx & 00111111 = 000XXXXX = hash & (oldCap-1);

You can continue to deduce that when hash & oldcap = 0, then M = 0. (The proof is not very rigorous AH)

This method is also understood directly in terms of source code and annotations.

FinalHashmap.node<k,v>[] Resize () {//There is nothing to say in front of this paragraph, the expansion table length of twice times, threshold usually is capacity * load_factor; If the table length is already//the biggest, then the threshold will also become integer.max_value.hashmap.node<k,v>[] Oldtab =table; intOldcap = (Oldtab = =NULL) ? 0: oldtab.length; intOldthr =threshold; intNewcap, Newthr = 0; if(Oldcap > 0) {                //This is because only the change of Threshode, the capacity has not changed, so node position does not need to change, directly returned.                 if(Oldcap >=maximum_capacity) {Threshold=Integer.max_value; returnOldtab; }                Else if((Newcap = oldcap << 1) < maximum_capacity &&Oldcap>=default_initial_capacity) Newthr= Oldthr << 1;//Double Threshold            }            Else if(Oldthr > 0)//initial capacity was placed in thresholdNewcap =Oldthr; Else{//Zero initial threshold signifies using defaultsNewcap =default_initial_capacity; Newthr= (int) (Default_load_factor *default_initial_capacity); }            if(Newthr = = 0) {                floatFT = (float) Newcap *Loadfactor; Newthr= (Newcap < maximum_capacity && ft < (float) maximum_capacity?                        (int) Ft:Integer.MAX_VALUE); } Threshold=Newthr; //re-create an array of a new lengthHashmap.node<k,v>[] NewTab = (hashmap.node<k,v>[])NewHashmap.node[newcap]; Table=NewTab; if(Oldtab! =NULL) {                //traverse the old table                 for(intj = 0; J < Oldcap; ++j) {Hashmap.node<K,V>e; if((e = oldtab[j])! =NULL) {                        //The old table is no longer used, so the direct assignment is null and can be recycledOLDTAB[J] =NULL; //if the next node of E is null, meaning there is no link table or tree structure, then the following table is recalculated, assigned to the new table                        if(E.next = =NULL) Newtab[e.hash& (newCap-1)] =e; //tree node changes, available in analysis                        Else if(EinstanceofHashmap.treenode) ((Hashmap.treenode<K,V>) (e). Split ( This, NewTab, J, Oldcap); Else{//Preserve Order//here is the redistribution of the list, note that some key in the original table will be computed to the same subscript, but in the new table is not necessarily//So the list may be broken up into 0-2 linked lists, why, can be described before ha. //So here we define two node pairs, one is lohead,lotail; the other is hihead,hitail.Hashmap.node<k,v> Lohead =NULL, Lotail =NULL; Hashmap.node<K,V> Hihead =NULL, Hitail =NULL; Hashmap.node<K,V>Next;  Do {                                //Looping throughNext =E.next; //E.hash & oldcap = = 0 node will be assigned to the same location, exactly, and the subscript of the original table is the same                                if((E.hash & oldcap) = = 0) {                                    if(Lotail = =NULL) Lohead=e; ElseLotail.next=e; Lotail=e; }                                //the rest of the nodes are assigned to a different location, which is the original table subscript + Oldcap                                Else {                                    if(Hitail = =NULL) Hihead=e; ElseHitail.next=e; Hitail=e; }                            }  while((e = next)! =NULL); //There is nothing here, and assigning values in the corresponding position can                            if(Lotail! =NULL) {Lotail.next=NULL; NEWTAB[J]=Lohead; }                            if(Hitail! =NULL) {Hitail.next=NULL; Newtab[j+ Oldcap] =Hihead; }                        }                    }                }            }            returnNewTab; }
View Code 

JAVA HASHMAP Parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.