Java HashMap Core Source code interpretation

Source: Internet
Author: User

This article hashmap the realization of the source code for a simple analysis. The version information of the HashMap source used is as follows:

/* * @ (#) Hashmap.java 1.73 07/03/13** Copyright 2006 Sun Microsystems, Inc. All rights reserved.* SUN proprietary/confidential. Use are subject to license terms. */
I. Overview

Each object in Java has a hash code, which can be obtained through the Hashcode () method. The value of Hashcode () is closely related to the Equals method of the object, which is the basis of whether the values of the two objects are equal, so we must override the Hashcode method when we override the Equals method of a class.

For example, the Hashcode method for string is:

 public  int   Hashcode () { int  H = hash;  if  (h = = 0 int  off = offset;  char  val[] = int  len = count;  for  (int  i = 0; i < len; I++) {h  = 31*h + Val[off ++ = H;}  return   H;}  

As you can see, the hash value of a string is s[0]31n-1 + s[1]31n-2 + ... + s[n-1], which is an integer. This means that all strings can be mapped to integers by hashcode (), because the number of integers in Java is limited (four bytes are positive or negative, the first bit is the sign bit-231 ~ 231-1), when s[0]31n-1 + s[1]31n-2 + ... + s[n-1] It may overflow when it is large enough to cause it to become negative. From the above we can see that two different strings may be mapped to the same integer, and there is a conflict. So Java developers chose the multiplier factor of 31, and try to make the results of each string map evenly distributed throughout the entire Java integer field.

After talking about the hash code of the Java object, let's take a look at today's protagonist Hashmap,hashmap can be seen as a Java implementation of the hash table. The key-value pair is stored in the HashMap, and the corresponding type is java.util.HashMap.Entry, so the data in the HASHMAP is stored in an array of Entry reference types in table. Here the key is an object, in order to map the object to a position in the table, we can find the remainder method, so we can use [Key's hashcode% table length] To calculate the position (of course, in the actual operation due to the need to consider the key on the table of the uniform distribution may need to do some processing of key hashcode).

Two. Source code parsing

The related property must first of all need an array of table, as the backbone of the data structure.

transient Entry[] table;

This defines a reference to an entry array. Continue to introduce several concepts to

Capacity capacity is the length of the Index Group table
Loadfactor loading factor, which is a ratio of the actual amount of/capacity capacity, in code This attribute is the maximum value of the load factor, the default size is 0.75
Threshold (threshold) represents a critical point in the amount of content that HashMap stores, and when the amount is larger than this value, it is necessary to exaggerate the table, which is to create a new twice-fold array and move the old elements over. threshold = (int) (capacity * loadfactor);

The Put method is detailed

 Publicv put (K key, V value) {if(Key = =NULL)            returnPutfornullkey (value); inthash =Hash (Key.hashcode ()); inti =indexfor (hash, table.length);  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; }} Modcount++;        AddEntry (hash, key, value, I); return NULL; }

In HashMap, our key can be null, so the first step is to handle the case of key null.
When key is non-null, you might think: Well, dividing it directly into the table length, but not here, but also like doing a hash, this is why? This has to look at indexfor (hash, table.length) method, this method is to determine the location of the

Static int indexfor (intint  length) {        return H & (Length-1);    } 

Can be found in the eye, because the length of the table in HashMap is 2n  (we take the operation into binary), so H & (length-1) is equivalent to h%length, which means that If you do not change the original hashcode, its removal of the lower length-1 bit will not have any effect on the position of key in the table, so long as the low length-1 position remains unchanged, regardless of the high level will conflict, so try to make the high point to its results also have an impact , and then made a hash of the hashcode again

 static  int  hash (int   h) { //  This function ensures so hashcodes that differ only by  //  constant multiples at each bit position has a bounded  //  number of collisions (approximately 8 at default load factor).         H ^= (H >>>) ^ (H >>> 12);  return  H ^ (H >>> 7) ^ (H >>> 4); }

When the location of the key is found, the entry linked list of the corresponding position is traversed, and if the key is present, the corresponding value is updated and the old value is returned. If it's a new key, add it in. Modcount is used to record the number of changes in the HASHMAP structure, which needs to be used in the fail-fast mechanism of hashmap (when a thread acquires a map cursor, another thread modifies the map, Then the thread that was intended to traverse will throw an exception). The AddEntry method is as follows

void addentry (intint  bucketindex) {    Entry<K,V> e = table[ Bucketindex];         New Entry<k,v>(hash, key, value, e);         if (size++ >= threshold)            Resize (2 * table.length);    }

Get method

 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; }

The Get method actually calculates the position of the table in the same way as the put, and then iterates through the linked list in the location, finding the entry with the hash value equal to the key and returning the value.

Java HashMap Core Source code interpretation

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.