[Java Basics] The things that HashMap

Source: Internet
Author: User

When it comes to hashmap, people who use the Java language are more familiar with it. Just talk about the hashmap we know today.

First, let's look at the HashMap class in Java

 Public class extends Abstractmap<k,v>    implements map<k,v>, cloneable, Serializable {    private  staticfinallong serialversionuid = 362498820763181265L; ...}

We can see that HashMap is a set of generic container, inherit the Abstractmap class, implement the map interface, cloneable interface, serializable interface, Abstractmap class is also an abstract class, part of the implementation of the map interface;

 Public Abstract class Implements Map<k,v> {...} ....}

The principle of hashmap is to use the principle of hash hash storage:

This picture is from Baidu on the search, took to use.

The principle is as follows:

1. In the new HashMap or put operation, will be pre-request a size of 2n array, the array is stored in node<k,v>[]; The elements of an array are references to a header node of a linked list;

2. When a node<k,v> is put, the Hashcode (K) & (len-1) is computed first to calculate the position in the array a[i];

3. If the position a[i] has not been filled, the node<k,v> will be stored directly at A[i];

4. If a[i] already has a value, it will add node<k,v>; to the end of the list in the form of a linked list

5. When the length of the list exceeds treeify_threshold-1, it is changed to TreeMap, reducing the time complexity of the search;

Through the above exposition, it is easy to understand the advantages of HashMap:

1. Can quickly locate the node position;

2. Can add nodes dynamically;

When analyzing the source code of JDK1.8.0_25, it is found that new HashMap is not immediately new, but instead puts the new operation on the put:

   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;  This. Threshold =tablesizefor (initialcapacity); }    /*** Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and the default load     Factor (0.75). *     * @paraminitialcapacity the initial capacity. * @throwsIllegalArgumentException If the initial capacity is negative. */     PublicHashMap (intinitialcapacity) {         This(initialcapacity, default_load_factor); }    /*** Constructs an empty <tt>HashMap</tt> with the default initial capacity * (+) and the default L     Oad factor (0.75). */     PublicHashMap () { This. loadfactor = Default_load_factor;//All other fields defaulted}

You can see that there are no new node nodes in the constructor, and the actual expansion hashmap capacity is in the resize method;

    FinalNode<k,v>[] Resize () {Node<k,v>[] Oldtab =table; intOldcap = (Oldtab = =NULL) ? 0: oldtab.length; intOldthr =threshold; intNewcap, Newthr = 0; if(Oldcap > 0) {            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; @SuppressWarnings ({"Rawtypes", "unchecked"}) Node<k,v>[] NewTab = (node<k,v>[])NewNode[newcap]; Table=NewTab; if(Oldtab! =NULL) {             for(intj = 0; J < Oldcap; ++j) {Node<K,V>e; if((e = oldtab[j])! =NULL) {Oldtab[j]=NULL; if(E.next = =NULL) Newtab[e.hash& (newCap-1)] =e; Else if(EinstanceofTreeNode) ((TreeNode<K,V>) (e). Split ( This, NewTab, J, Oldcap); Else{//Preserve OrderNode<k,v> Lohead =NULL, Lotail =NULL; Node<K,V> Hihead =NULL, Hitail =NULL; Node<K,V>Next;  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); if(Lotail! =NULL) {Lotail.next=NULL; NEWTAB[J]=Lohead; }                        if(Hitail! =NULL) {Hitail.next=NULL; Newtab[j+ Oldcap] =Hihead; }                    }                }            }        }        returnNewTab; }

So we can understand the reason why he is efficient.

Finally, the matter between HashMap and Hashtable;

1. The two inherit differently:

 Public class extends abstractmap<k,v>Publicclassextends dictionary<k,v>

2. Synchronized is used in Hashtable to achieve thread safety, while HashMap requires users to control thread safety.

3. HashMap k,v can be null, if V is null, indicating that the key value has not been stored;

4. The hash value is computed differently, and Hashtable directly uses the object's hashcode. The hash value is recalculated by the HashMap. The hash of the HASHMAP is calculated as follows:

    Static Final int Hash (Object key) {        int  h;         return null) ? 0: (H = key.hashcode ()) ^ (h >>>);    }

In Hashtable, only the int hash = Key.hashcode () is used to calculate;

5. Hashtable and hashmap the initial size and expansion of the array of their two internal implementations. The default size of the hash array in Hashtable is 11, and the increment is old*2+1. The default size of the hash array in HashMap is 16, and must be a 2 index.

Reference post: http://www.cnblogs.com/devinzhang/archive/2012/01/13/2321481.html

The ability is limited, if has the mistake, kindly pointed out, please advise.

[Java Basics] The things that HashMap

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.