Explanation of Java HashMap core source code
This article analyzes the source code of HashMap. The version of the HashMap source code used is as follows:
/** @(#)HashMap.java 1.73 07/03/13** Copyright 2006 Sun Microsystems, Inc. All rights reserved.* SUN PROPRIETARY/CONFIDENTIAL. Use is 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 and is the basis for equality of the values of the two objects. Therefore, when we override the equals method of a class, we must also overwrite the hashCode method.
For example, the hashCode method of String is:
public int hashCode() {int h = hash;if (h == 0) {int off = offset;char val[] = value;int len = count;for (int i = 0; i < len; i++) {h = 31*h + val[off++];}hash = h;}return h;}
It can be seen that the hash value of a string is s [0]31n-1 + s [1]31n-2 +... + S [n-1] is an integer. That is to say, all strings can be mapped to the Integer Range through hashCode (), because the number of integers in java is a limited number of four bytes plus or minus, and the first digit is the symbol bit-231 ~ 231-1), when s [0]31n-1 + s [1]31n-2 +... + S [n-1] may overflow when it is large enough, resulting in a negative value. From the above situation, we can see that two different strings may be mapped to the same integer, causing a conflict. Therefore, java developers select the 31 multiplier to make the results of string ing evenly distributed throughout the java integer domain.
After talking about the hash code of a java object, let's take a look at HashMap, the main character of today. HashMap can be seen as a hash table implemented by Java. HashMap stores key-value pairs and corresponding types are java. util. HashMap. Entry. Therefore, data in HashMap is stored in an array table of Entry reference type. Here, the key is an object. to map the object to a position in the table, we can use the remainder method, therefore, we can use [key hashCode % table length] to calculate the location. Of course, in actual operations, we need to consider the even distribution of keys on the table. We may need to do some operations on the key hashCode. processing ).
Ii. source code parsing
An array table is required as the backbone of the data structure.
transient Entry[] table;
A reference to the Entry array is defined here. Continue to introduce several concepts
Capacity is the length of the index group table
LoadFactor: the ratio of actual storage volume to capacity. In the code, this attribute describes the maximum value of the load factor. The default size is 0.75.
Threshold) indicates a critical point of the number of contents stored in hashmap. When the storage volume is larger than this value, you need to exaggerate the table, that is, create a two-fold array, and transfer the old elements. Threshold = (int) (capacity * loadFactor );
Detailed description of put Method
public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); int i = 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); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; }
In HashMap, our key can be null, so the first step is to handle the case where the key is null.
When the key is not null, you may think: Well, it's just like dividing the modulo with the table length, but it's not here, but it's like doing a hash. Why? The indexFor (hash, table. length) method is used to determine the storage location.
static int indexFor(int h, int length) { return h & (length-1); }
We can see from the eye that in HashMap, the table length is 2n (we replace all the operations with binary values), so h & (length-1) this is equivalent to h % length. That is to say, if the original hashCode is not transformed, the part after removing the low length-1 won't affect the position of the key in the table, in this way, as long as we keep the low length-1 bit unchanged, no matter how high it will conflict, we can try to make the high level affect the result, so we made another hash of hashCode.
static int hash(int h) { // 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); }
When the position corresponding to the key is found, the linked list of the Entry at the corresponding position is traversed. If there is a key, the corresponding value is updated and the old value is returned. If it is a new key, add it. ModCount is used to record the number of times the hashmap structure changes. In the fail-fast mechanism of hashmap, when a thread obtains the map cursor, another thread modifies the map structure, so the thread that was originally prepared to traverse will throw an exception ). The addEntry method is as follows:
void addEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); if (size++ >= threshold) resize(2 * table.length); }
Get Method
public V get(Object key) { if (key == null) return getForNullKey(); int hash = 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))) return e.value; } return null; }
The get method is actually to calculate the location of the key in the table using the same method when put, and then traverse the linked list in the location, locate the Entry with the same hash value and key and return the value.