JDK1.7 HashMap source code analysis, jdk1.7hashmap

Source: Internet
Author: User

JDK1.7 HashMap source code analysis, jdk1.7hashmap
Overview

HashMap is a basic data type used to store keys and values in Java. understanding its internal implementation can help us compile more efficient Java code.

This article mainly analyzesJDK1.7In HashMap implementation, the HashMap in JDK1.8 is different from this, and will be summarized later.

Body HashMap Overview

HashMap obtains the storage location based on the hashCode value of the key. In most cases, it can be directly located to its value, so it has a fast access speed, but the traversal order is uncertain. HashMap allows a maximum of null keys for one record and null values for multiple records. HashMap is non-thread safe. At any time, multiple threads can write HashMap at the same time, which may cause data inconsistency. To ensure thread security, you can use the synchronizedMap method of Collections to make HashMap thread-safe, or use ConcurrentHashMap.

Shows the storage structure of HashMap:

Public V put (K key, V value) {// if the table is empty, initialize table if (table = EMPTY_TABLE) {inflateTable (threshold );} if (key = null) return putForNullKey (value); // calculate the key's hash value int hash = hash (key); // calculate the key's hash value and table. length calculates the location of the KEY int I = indexFor (hash, table. length); // judge whether there are repeated values. If yes, replace the old value with the new value and return the old value 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); return oldValue;} // The number of modifications plus one, used to determine whether the HashMap element has modified modCount ++ during HashMap iteration; // Add key addEntry (hash, key, value, I); return null ;}InflateTable-initialize the internal array of HashMap

Private void inflateTable (int toSize) {// calculate the capacity based on toSize, that is, the n int capacity = roundUpToPowerOf2 (toSize) of 2 greater than toSize );.........} Private static int roundUpToPowerOf2 (int number) {// assert number> = 0: "number must be non-negative"; return number >=maximum_capacity? MAXIMUM_CAPACITY: (number> 1 )? Integer. highestOneBit (number-1) <1): 1;} public static int highestOneBit (int I) {// HD, figure 3-1 I | = (I> 1); I | = (I> 2); I | = (I> 4 ); I | = (I> 8); I | = (I> 16); return I-(I >>> 1 );}

Key Method Integer. highestOneBit (number-1) <1). The result of this method is to obtain the nth power of 2 that is greater than the given value.

Several concepts are described before the explanation:

<: In binary format, all digits are moved to the right to the corresponding number of digits. The high position is removed (discarded), and the low position is filled with zero. If the number does not overflow, for positive and negative numbers, moving one to the left is equivalent to multiplying the power of 1 by 2, and moving n to the left is equivalent to multiplying the power of N2;

>>: Shifts all numbers to the right in the binary format, and removes (discards) the number at the low position. Signs are filled at the high position, that is, zeros are filled by positive numbers, and 1 is filled by negative numbers. Shifts one to the right is equivalent to dividing 2, and shifts n to the right is equal to dividing by 2 to the Npower.

>>>: Shifts right without a symbol. Ignore the symbol bit. The empty space is filled with 0.

 

Let's take the number 10 as an example. After (number-1) <1 = 18, the binary value is 10010.

I | = (I> 1) that is: 10010 | 01001 = 11011

I | = (I> 2) that is: 11011 | 00110 = 11111

I | = (I> 4) that is: 11111 | 00001 = 11111

......

In fact, this step changes all the bits after the highest bit of I to 1.

Then I-(I >>> 1) that is: 11111-01111 = 10000 (16)

In this step, we change the highest bit and all the subsequent values to 0, so that we can find the Npower (16) of the second closest to 10)

As to why we should set the Size of the array to the N power of 2, we will talk about it later.

Hash-calculate the hash value of the Key
final int hash(Object k) {    int h = hashSeed;    if (0 != h && k instanceof String) {        return sun.misc.Hashing.stringHash32((String) k);    }    h ^= k.hashCode();    // This function ensures that hashCodes that differ only by    // constant multiples at each bit position have a bounded    // number of collisions (approximately 8 at default load factor).    h ^= (h >>> 20) ^ (h >>> 12);    return h ^ (h >>> 7) ^ (h >>> 4);}

According to the above comment, we can see that the hash value used in HashMap is not the direct hashCode of the Key, but calculated in series.

The function of calculating the hash value is to avoid hash collision and minimize the generation of one-way linked lists, because the time complexity of searching an element in a linked list is O (n ).

IndexFor-calculate the array location corresponding to the Key
static int indexFor(int h, int length) {    // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";    return h & (length-1);}

I don't understand this method for the first time. Shouldn't I use h % length? In fact, a very clever method is used to obtain the remainder.

In a computer, CPU Division operations and remainder operations consume a long CPU cycle. Generally, dozens of CPU cycles are used, while displacement operations and bit operations only use one CPU cycle.

In this way, where performance requirements are high, bitwise operations can be used to replace common division and remainder operations. There are many such examples in the JDK source code.

In order to be able to use the bitwise operation to obtain the remainder, length must be the Npower of 2, which is also required by the initialization of the array above, and then use h & (length-1 ), you can obtain the remainder. Please search for the specific algorithm derivation.

Let's use an example to illustrate that, for example, if a Key is computed with a hash of 21 and a length of 16:

Direct remainder operation: 21% 16 = 5

Bitwise operation: 10101 (21) & 01111 (16-1) = 00101 (5)

Wow, this is the charm of computer computing, and this is the role of algorithms.

AddEntry-add data
Void addEntry (int hash, K key, V value, int bucketIndex) {// If the size is greater than or equal to threshold, and the position of the array is not null, expand the array if (size> = threshold) & (null! = Table [bucketIndex]) {resize (2 * table. length); hash = (null! = Key )? Hash (key): 0; bucketIndex = indexFor (hash, table. length);} createEntry (hash, key, value, bucketIndex );}

Threshold: number of keys that can be stored by HashMap. If the size is greater than threshold, it indicates that HashMap is too saturated and is prone to hash collisions, resulting in the generation of one-way linked lists.

In the inflateTable method, we can see that

threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);

Therefore, this value is calculated by the capacity and load factor (loadFactor default: 0.75) of HashMap.

The smaller the loadFactor, the more frequent the expansion of the same capacity. The advantage is that HashMap will be very large, and the probability of hash collision will be smaller, but more memory is needed, this is the so-called space change time.

Note that the original capacity will be multiplied by 2 directly during resizing to meet the n condition of length 2.

The createEntry statement is to save the key and value to the corresponding position of the array.

GET
Final Entry <K, V> getEntry (Object key) {if (size = 0) {return null ;} // obtain the hash value int hash = (key = null) using the same algorithm as the algorithm used for addition )? 0: hash (key); // get the data directly from the array's response position. If the hash and key are the same, the 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! = Null & key. equals (k) return e;} return null ;}

It is very simple and fast to get, and all the work done when adding is to get quick work.

Summary

HashMap is a very efficient Key-Value data structure. The time complexity of GET is: O (1 )~ O (n), we need to pay attention to the following points when using HashMap:

1. When declaring HashMap, it is best to use a constructor with initialCapacity to input the maximum size of data to avoid internal array resize;

2. When the performance requirement is high, you can set the loadFactor to be smaller than the default value of 0.75, so that the hash value is more dispersed and the space is used for time;

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.