Java--hashmap Source Code parsing

Source: Internet
Author: User

Interest-induced research on the source of HashMap, write down their understanding, based on JDK1.8.

This article probably analyzes HashMap's put (), get (), resize () three methods.

First let's look at the put () method.

     Public v put (K key, V value) {        returnfalsetrue);    }
    /*** Implements Map.put and Related methods * *@paramHash hash for key *@paramKey The key *@paramvalue the value to put *@paramonlyifabsent If True, don ' t change existing value *@paramevict if False, the table is in creation mode. * @returnprevious value, or null if none*/    FinalV Putval (intHash, K key, V value,BooleanOnlyifabsent,Booleanevict) {Node<k,v>[] tab; Node<k,v> p;intN, I; if(tab = table) = =NULL|| (n = tab.length) = = 0) n= (Tab =resize ()). length; if(p = tab[i = (n-1) & hash]) = =NULL) Tab[i]= NewNode (hash, key, value,NULL); Else{Node<K,V>e;            K K; if(P.hash = = Hash &&((k= p.key) = = Key | | (Key! =NULL&&Key.equals (k)))) E=p; Else if(pinstanceofTreeNode) e= ((treenode<k,v>) p). Puttreeval ( This, tab, hash, key, value); Else {                 for(intBincount = 0;; ++Bincount) {                    if((e = p.next) = =NULL) {P.next= NewNode (hash, key, value,NULL); if(Bincount >= treeify_threshold-1)//-1 for 1sttreeifybin (tab, hash);  Break; }                    if(E.hash = = Hash &&((k= e.key) = = Key | | (Key! =NULL&&Key.equals (k))))  Break; P=e; }            }            if(E! =NULL) {//existing mapping for keyV OldValue =E.value; if(!onlyifabsent | | oldValue = =NULL) E.value=value;                Afternodeaccess (e); returnOldValue; }        }        ++Modcount; if(++size >threshold) resize ();        Afternodeinsertion (evict); return NULL; }

1. First calculate the hash value of key by hash (key)

Putval (hash (key), key, value, False, True)

2. Since HashMap actually stores the data in the table array, it is first necessary to determine if the table array has been initialized, and if not initialized, call the Resize () method to initialize the table.

if Null | | (n = tab.length) = =0            )= (Tab = resize ()). length;

3. The index of the array is computed by hashing and (n-1), the root table[index] Determines whether it is null, and if NULL then it is deposited directly into that location.

if NULL )            null);

4. If the table[index] is not NULL, then the location has collided and needs to be judged

5. If you judge the P.key=key&&p.hash=hash on the table[index] position p, then the value is replaced, that is, the key is guaranteed to be unique.

6. If the 5 condition is not met, then the table[index] position p is two fork tree, then Treenode.puttreeval () is called to insert the two-fork tree node.

Else if instanceof TreeNode)                 = ((treenode<k,v>) p). Puttreeval (This, tab, hash, key, value);

7. If the 5,6 condition is not met, the linked list is used to insert the node: Loop through the p.next until a null position is found for insertion.

                 for(intBincount = 0;; ++Bincount) {                    if((e = p.next) = =NULL) {P.next= NewNode (hash, key, value,NULL); if(Bincount >= treeify_threshold-1)//-1 for 1sttreeifybin (tab, hash);  Break; }                    if(E.hash = = Hash &&((k= e.key) = = Key | | (Key! =NULL&&Key.equals (k))))  Break; P=e; }

8. In the above 5,6,7 three steps, if P.key=key&&p.hash=hash is found, the value substitution will be performed and oldvalue will be replaced with NewValue.

            if NULL // existing mapping for key                V oldValue = e.value;                 if NULL )                    = value;                Afternodeaccess (e);                 return oldValue;            }

9. Count +1, and determine whether the current number is greater than table[] 2/3, if it is greater then use resize () to expand the table.

10. The entire put () is complete.

Let's look at the Get () method again.

     Public V get (Object key) {        Node<K,V> e;         return NULL NULL : E.value;    }
    /*** Implements Map.get and Related methods * *@paramHash hash for key *@paramKey The key *@returnthe node, or null if none*/    FinalNode<k,v> GetNode (inthash, Object key) {Node<k,v>[] tab; Node<k,v> First, E;intN;        K K; if(tab = table)! =NULL&& (n = tab.length) > 0 &&( First= tab[(n-1) & hash])! =NULL) {            if(First.hash = = Hash &&//Always check first node(k = first.key) = = Key | | (Key! =NULL&&Key.equals (k)))) returnFirst ; if((E = first.next)! =NULL) {                if(FirstinstanceofTreeNode)return((treenode<k,v>). Gettreenode (hash, key);  Do {                    if(E.hash = = Hash &&((k= e.key) = = Key | | (Key! =NULL&&Key.equals (k)))) returne; }  while((E = e.next)! =NULL); }        }        return NULL; }

1. First determine if table[] is empty, determine whether the table[index is empty by hashing the index, or null if any of the entries is empty.

2. Determine table[index] hash and key are all the same as the lookup, if the hash and key are the same, then directly return to the table[index].

if // Always Check first node                null && key.equals (k                )))return first;

3. If the condition 2 is not met, then determine whether next of table[index] is empty, and return null if NULL.

4. If next of table[index] is not empty, then determine whether it is a two-fork tree, or if it is two fork tree directly using the Gettreenode () method to find.

if instanceof TreeNode)                     return ((treenode<k,v>) first). Gettreenode (hash, key);

5. If it is not a binary tree, then use the list directly to find the way.

 Do {                    if (E.hash = = Hash                        &&null && key.equals (k))))                         return e;                  while null);

6. Complete the Get () method at this point.

Java--hashmap Source code parsing

Related Article

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.