"Java Improvement"---hashmap parsing (i)

Source: Internet
Author: User

HashMap Analysis (I.)

Usually used HashMap and did not have a little in-depth to understand it, I spend some time to go inside in-depth, found that it is more difficult to understand than ArrayList, a lot of things are not very understanding and so on after their own knowledge more rich in come to understand.

There are arrays and linked lists in the data structure that can be stored, but these are basically two extremes.

array: The array storage interval is continuous and occupies a serious memory, so the space is very complex. But the binary finding time of the array is small and the complexity is O (1); The array is characterized by: easy addressing, insertion and deletion difficulties;

Linked list : The chain table storage interval is discrete, the memory is relatively loose, so the space complexity is very small, but time complexity is very large, up to O (N). The list is characterized by difficult addressing, easy insertion and deletion .

data structure of HashMap

HashMap is actually a "chain-table hash" of the data structure, that is, the combination of arrays and linked lists. Take a look at the following picture; to understand:

As you can see, the bottom of the HashMap is an array structure, and each item in the array is a linked list. When a new HashMap is created, an array is initialized.

Transientstaticclassimplements map.entry<k,v> {      Final  K key;    V value;    Entry<K,V> next;     Final int Hash;    ...}

As you can see, Entry is the element in the array, and each map.entry is actually a key-value pair, which holds a reference to the next element, which forms the list.

Access implementation of HashMap

Store

 Publicv put (K key, V value) {//The hashmap allows null keys and null values to be stored. //when key is null, the Putfornullkey method is called, and value is placed in the first position of the array.     if(Key = =NULL)        returnPutfornullkey (value); //The hash value is recalculated based on the keycode of the key.     inthash =Hash (Key.hashcode ()); //searches for the index of the specified hash value in the corresponding table.     inti =indexfor (hash, table.length); //if the Entry at the I index is not NULL, the next element of the E element is traversed continuously through the loop.      for(entry<k,v> e = table[i]; E! =NULL; E =e.next) {Object k; if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) {V OldValue=E.value; E.value=value; E.recordaccess ( This); returnOldValue; }    }    //If the entry at the I index is null, there is no entry here. modcount++; //adds the key, value, to the I index. addentry (hash, key, value, I); return NULL;}

As can be seen from the source code above: When we put the element in the HashMap, we first recalculate the hash value according to the key's hashcode, according to the hash is worth the position of the element in the array (that is, subscript), if the array is already stored in the position of other elements, Then the elements in this position will be stored in the form of a linked list, the newly added ones placed in the chain head, the first to join in the end of the chain. If the array has no elements at that position, the element is placed directly at that position in the array.

The Ddentry (hash, key, value, I) method places the Key-value pair at the I index of the array table, based on the calculated hash value. AddEntry is a way for HASHMAP to provide a package access to the code as follows:

voidAddEntry (intHash, K key, V value,intBucketindex) {    //gets the Entry at the specified Bucketindex indexEntry<k,v> e =Table[bucketindex]; //Place the newly created Entry into the Bucketindex index and let the new Entry point to the original EntryTable[bucketindex] =NewEntry<k,v>(hash, key, value, E); //if the number of key-value pairs in the Map exceeds the limit    if(size++ >=threshold)//extends the length of the table object to twice times the original. Resize (2 *table.length);}

When the system decides to store the Key-value pair in the HashMap, it does not take into account the value in entry, but only calculates and determines the storage location of each entry based on key. We can take the value of the Map collection as a subsidiary of the key, and when the system determines where the key is stored, value is stored there.

Read

 PublicV get (Object key) {if(Key = =NULL)        returnGetfornullkey (); inthash =Hash (Key.hashcode ());  for(Entry<k,v> e =table[indexfor (hash, table.length)]; E!=NULL; E=e.next) {Object k; if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) returnE.value; }    return NULL;}

With the hash algorithm stored above as the basis, it is easy to understand this code. From the source code above, you can see:

When a get element is obtained from HashMap, the hashcode of the key is computed first, an element in the corresponding position in the array is found, and the required element is found in the linked list of the corresponding position through the Equals method of key.

Induction

Simply put, HashMap at the bottom of the key-value as a whole to deal with, this whole is a Entry object. The HashMap bottom uses a entry[] array to hold all key-value pairs,

When a Entry object needs to be stored, the hash algorithm is used to determine where it is stored in the array, and where it is stored in the linked list on the array location according to the Equals method; When a Entry is required to be removed,

It also finds its storage location in the array based on the hash algorithm, and then extracts the entry from the linked list at that location according to the Equals method.

hashmap Source interpretation                          ,         &NB Sp                          ,         &NB Sp              

       hashmap There are two parameters that affect its performance: initial capacity and load factor . The default initial capacity is 16 0.75 Span style= "font-family: Song body; Font-size:10pt ". The capacity is the hash table in the bucket (Entry array )

A load factor is a scale in which a hash table can reach a full amount before its capacity increases automatically. Doubles the capacity by calling the Rehash method when the number of entries in the hash table exceeds the product of the load factor to the current capacity .

the member variables defined in HASHMAP are as follows:

 Static Final intdefault_initial_capacity = 16;//The default initial capacity is 16 and must be a power of 2  Static Final intmaximum_capacity = 1 << 30;//30-time Maximum capacity of 2  Static Final floatDefault_load_factor = 0.75f;//default load Factor 0.75    transientEntry<k,v>[] table;//entry array, hash table, length must be a power of 2  transient intSize//number of saved elements  intThreshold//the critical value of the next expansion, the Size>=threshold will be enlarged  Final floatLoadfactor;//load Factor

HashMap altogether overloaded 4 construction methods, respectively:

HashMap ()
            constructs an empty   with default initial capacity (16) and default load factor (0.75); hashmap

HashMap (int initialcapacity)
            Constructs a null with the specified initial capacity and default load factor (0.75)   hashmap .

HashMap (int initialcapacity, float  Loadfactor)
           Constructs an empty   with the specified initial capacity and load factor; hashmap

HashMap(Map<? extendsK,? extendsV> m)
Constructs a mapping relationship with the specified Map the same HashMap.

Take a look at the third method of constructing the source code, the other constructor method is ultimately called it.

 PublicHashMap (intInitialcapacity,floatloadfactor) {      //argument, illegal throw run-time exception    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); //Find a power of 2 >= initialcapacity//you need to pay attention here .    intCapacity = 1;  while(Capacity <initialcapacity) Capacity<<= 1; //setting the load factor     This. Loadfactor =Loadfactor; //set the next critical value for expansionThreshold = (int) Math.min (capacity * Loadfactor, maximum_capacity + 1); //initializing a hash tableTable =NewEntry[capacity]; Usealthashing= sun.misc.VM.isBooted () &&(Capacity>=holder.alternative_hashing_threshold);  Init (); }  

This post is here.

Attached to Daniel Blog: HashMap Depth Analysis (a)

HashMap depth Analysis (II.)

Java Container (iv): the implementation principle of HashMap (Java 7)

Schematic set 4:hashmap

Stones, the speed of success must be more than the speed of parents old! Ensign "5"




"Java Improvement"---hashmap parsing (i)

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.