A brief analysis of HashMap in Java

Source: Internet
Author: User

? HashMap and HashSet are two important members of the Java Collection Framework, where HashMap is a common implementation class for the Map interface, and HashSet is a common implementation class for the Set interface. Although the interface specifications implemented by HASHMAP and HashSet are different, their underlying Hash storage mechanism is exactly the same, even HashSet itself is implemented using HASHMAP.

The Hash storage mechanism is analyzed through the source code of HASHMAP and HashSet.
collections and References  
Just like an array of reference types, when we put a Java object into an array, we don't actually put the Java object in the array, just put the object's reference into the array, each array element is a reference variable.

hashmap Storage implementation

Hashmap<string , double> map = new hashmap<string , double > (); Map.put ("language"  , 80.0); System.out.println ("Language hashcode: "  + map.get ("language"). Hashcode ()); Map.put ("language"  , 80.0); System.out.println ("Language change score after hashcode1: "  + map.get ("language"). Hashcode ()); Map.put ("Language",  80.2); System.out.println ("Language Changes hashcode2: "  + map.get ("language"). Hashcode ()); Map.put ("Mathematics",  89.0); Map.put ("English",  78.2); System.out.println ("Mathematical hashcode: "  + map.get ("Mathematics"). Hashcode ()); System.out.println ("English hashcode: " +map.get ("English"). Hashcode ()); Map.put (null , 78.5); Map.put ("null"  , 78.6); System.out.println ("null hashcode: " +map.get (null)); System.out.println ("null hashcode: "  + map.get (null). Hashcode ()); System.out.println ("\" null\ " hashCode: " +map.get ("null")); System.out.println ("\" null\ " hashCode: " +map.get ("null"). Hashcode ());

The results after the run are as follows:

Chinese hashcode:1079246848 language change score after hashcode1:1079246848 language change score HashCode2:-1936146431 Mathematics hashcode:1079394304 English Hashcode:- 1935720447null hashcode:78.5null hashcode:1079222272 "null" hashcode:78.6 "NULL" hashcode:641056768

Look at the source code of the put (K key, V value) method of the HashMap class:

  /**     * associates the specified value with  the specified key in this map.     * if the  map previously contained a mapping for the key, the old      * value is replaced.     *      *  @param  key key with which the specified value  is to be associated     *  @param  value value  to be associated with the specified key     *   @return  the previous value associated with <tt>key</tt>,  Or     *         <tt>null</tt > if there was no mapping for <tt>key</tt>.     *           (a <tt>null</tt> return can also  indicate that the map     *          previously associated <tt>null</tt> with <tt>key</tt>.)      */    public v put (K key, V value)  {            if  (Key == null)             return putfornullkey (value);             //  if  key  is  null, Call the  putForNullKey  method for processing          int hash =  hash (Key.hashcode ());nbsp;           //  according to the  key   keycode   Calculation  Hash  Values           int i =  Indexfor (hash, table.length);             //   Search the index of the specified  hash  value in the corresponding  table                 //  if  Entry  at  i  index is not  null, iterate through the loop repeatedly  e  Element's next element           for  (entry<k,v> e =  table[i]; e != null; e = e.next)  {             Object k;             //  find the specified  key  with the  key  equality to be placed (the hash  value is the same through  equals  compare put back  true) &NBSP;&NBSP;&NBSP;&NBsp;          if  (e.hash == hash & &  ((k = e.key)  == key | |  key.equals (k))  {                 V oldValue = e.value;                 e.value = value;                 e.recordaccess (This);                 return oldValue;             }        }             //  if  Entry  at  i  index As  null, indicating that there is no  entry       modcount+ here+;      //  add  key, value  to  i  index       addentry (hash, key, value, i);     return null;}

As can be seen from the above program: 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.

This also shows that we can completely consider 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.

The method above provides a method for calculating the hash code based on the Hashcode () return value: hash (), which is a purely mathematical calculation with the following method:

static int hash (int h) {h ^= (H >>> a) ^ (h >>> 12);   Return h ^ (H >>> 7) ^ (H >>> 4); }

The bitwise XOR operator is the binocular operation.

>>> is converted to a binary right shift, empty out of the complement 0

Bitwise XOR OR operator ^

For example: 10100001^00010001=10110000 0^0=0,0^1=1 0 xor or any number = any number 1^0=1,1^1=0 1 xor or any number = any number of inverse any number xor or self = Place yourself 0

For any given object, the hash code value computed by the program call hash (int h) method is always the same as long as its hashcode () return value is the same. The program then calls the indexfor (int h, int length) method to calculate at which index the object should be stored in the table array. The code for the indexfor (int h, int length) method is as follows:

static int indexfor (int h, int length) {return H & (LENGTH-1); }

This method is very ingenious, it always through H & (table.length-1) to get the location of the object-while the HashMap of the underlying array is always 2 of the n-th square.

When length is always a multiple of 2, H & (Length-1) will be a very ingenious design:

Assuming h=5,length=16, then H & Length-1 will get 5;

If h=6,length=16, then H & Length-1 will get 6;

......

If h=15,length=16, then H & Length-1 will get 15;

But when H=16, length=16, then H & Length-1 will get 0;

When H=17, length=16, then H & length-1 will get 1 ...

This ensures that the computed index value is always within the index of the table array.


The above program also calls the AddEntry (hash, key, value, I); Code, where AddEntry is a method that HASHMAP provides access to a package that is used only to add a key-value pair. Here is the code for the method:
Void addentry (Int hash, k key, v value, int bucketindex)     {       //  get  Entry  at the specified  bucketIndex  index       Entry<K,V> e = table[bucketIndex];      // ①      //  add newly created  Entry  into  bucketindex   Index, and let the new  Entry  point to the original  entry       table[bucketindex]  = new Entry<K,V> (hash, key, value, e);        //  if the number of  key-value  pairs in  Map  exceeds the limit       if   (Size++ >= threshold)            //   Expands the  table  object's length to  2  times.           resize (2 * table.length);     // ②  } 

The code for the above method is simple, but it contains a very elegant design: The system always places the newly added Entry object in the Bucketindex index of the table array--If a Entry object is already at the Bucketindex index, the newly added Entry Like pointing to the original Entry object (producing a Entry chain), if there is no Entry object at the Bucketindex index, that is, the e variable of the program ① code above is null, that is, the newly placed Entry object points to null, that is, no resulting Entry Chain.

The table used in the above program is actually an ordinary array, each array has a fixed length, the length of the array is HashMap capacity. The HASHMAP contains the following constructors:

* HASHMAP (): Constructs a HashMap with an initial capacity of 16 and a load factor of 0.75.     * HASHMAP (int initialcapacity): Build a HashMap with an initial capacity of initialcapacity and a load factor of 0.75. * HASHMAP (int initialcapacity, float loadfactor): Creates a HashMap with the specified initial capacity, specified load factor.

When creating HashMap, there is a default load factor (load factor) with a default value of 0.75, which is a tradeoff between time and space costs:

Increasing the load factor can reduce the memory space occupied by the Hash table (that is, the Entry array), but it will increase the time overhead of querying the data, and the query is the most frequent operation (the HashMap get () and the Put () method use the query);

Reducing the load factor increases the performance of the data query, but increases the amount of memory occupied by the Hash table.

Having mastered the above knowledge, we can adjust the value of load factor according to the actual need when we create HASHMAP, if the program is concerned about space overhead, memory is more tense, the load factor can be increased appropriately, if the program is more concerned about the time overhead, A more comfortable memory can reduce the load factor appropriately.

Typically, programmers do not need to change the value of the load factor.





A brief analysis of HashMap in Java

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.