HashMap: Source code (constructor, put, resize, get, remove, replace)

1. Constants

(1) Default table size, 1 shifts left four bits to 8

 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

(2) Maximum table length

 static final int MAXIMUM_CAPACITY = 1 << 30;

(3) Default load factor size:

 static final float DEFAULT_LOAD_FACTOR = 0.75f;

(4) Tree threshold

    static final int TREEIFY_THRESHOLD = 8;

(5) Tree downgrade to chain table threshold

    static final int UNTREEIFY_THRESHOLD = 6;

(6) Upgrade hash table elements to trees after 64

  static final int MIN_TREEIFY_CAPACITY = 64;

(7) Hash list (hash table)

  transient Node<K,V>[] table;

(8) Number of elements in the current hash table:

 transient int size;

(9) Number of modifications to the current hash table

 transient int modCount;

(10) Expansion threshold: trigger expansion when elements of a hash table exceed the threshold

    int threshold;

(11) Load factor

  final float loadFactor;


2. Construction methods

(1) Construction method:

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);

initialCapacity must be greater than zero, maximum MAXIMUM_CAPACITY, loadFactor must also be greater than zero, these are some checks

    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;

Returns a number greater than or equal to the current value cap, and the number must be a power of 2.


n=10-1=9 (doubles if not reduced)

1001 | 0100 (one bit to the right) = 1101

1101 | 0011 (two places to the right)=1111

1111 | 0000 (four digits right) =1111

.... ...

... ...

return 15+1=16 (after adding 1, one digit in, the next digits become zero)


3. put Method

(1) is a doll's method: call putVal method:

  public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);

Hash method: hashCode is perturbed to get a hash value. The hash value is calculated with the length of the table to get the position in the hash table. This perturbation function is the hash function.

Disturbance function: Let the hexadecimal digits of the key hash also participate in the routing operation


(2) hash method

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

If the key is empty, the hash value is zero. If it is not empty, h and H are shifted 16 bits to the right in order for the higher 16 bits of the key's hash value to also participate in the operation:


If hashtable is not very large (16), the higher sixteen can be involved.


(3) putVal method

 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
//tab: a Hash list that references the current hashMap
//p: The element representing the current Hash list
//n: Represents the length of a Hash list array
//i: Represents the result of routing addressing Node
<K,V>[] tab; Node<K,V> p; int n, i;
//Delayed initialization logic that initializes the most memory-consuming Hash list in the hashMap object the first time putValue is called
if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length;
//In the simplest case: the barrel found by addressing, which happens to be null, throw the current k--v=>node in
if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else {
//e: If not null, an element of the key identical to the key value currently being inserted was found
//k: represents a temporary key Node
<K,V> e; K k;
//Represents the element in the bucket, identical to the key of the currently inserted element, indicating that a replacement is required later
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else {
//What happens with a linked list, and the header element of the linked list is not consistent with the key element we want to insert
for (int binCount = 0; ; ++binCount) {
//If the condition is true, it means that the last element is iterated over, and no node matching the key you are inserting is found.
//Indicates that you need to add to the end of the current list area
if ((e = p.next) == null) { p.next = newNode(hash, key, value, null);
//If the condition is valid, it means that the length of the current chain table has reached the tree standard and needs to be tree
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//Tree Operation
treeifyBin(tab, hash); break; }
//If the condition is true, the element with the same key has been found and needs to be replaced
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } }
//e is not equal to null, condition is valid means that a data identical to the key you inserted has been found and needs to be replaced
if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } }
//Represents the number of times the hash structure has been modified, and the value of the replacement node element is not counted
//Insert a new element that triggers expansion if the value since expansion is greater than the expansion threshold
if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }

If the key is the same as the current key, it is no longer inserted


4. resize method

(1) Source Code

final Node<K,V>[] resize() {
//oldTab, refers to the pre-expansion hash table Node
<K,V>[] oldTab = table;
//oldCap represents the length of the table array before expansion
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//oldThr represents the pre-expansion threshold, which triggers this expansion
int oldThr = threshold;
//newCap: The size of the Table array after expansion
//newThr: Conditions for next trigger expansion after expansion
int newCap, newThr = 0;
//If the condition is true, the Hash list in hashMap has been initialized and is a normal expansion
if (oldCap > 0) {
//Once the table array size before expansion reaches the maximum threshold, it is not expanded and the maximum expansion condition is set to int maximum
if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; }
//oldCap doubles the array by moving one bit to the left and assigns it to newCap, which is less than the array maximum limit and the threshold before expansion >=16
//In this case, the next expansion threshold is equal to doubling the current threshold
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY;//16 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab;
//Note that table s are not empty until HashMap is expanded
if (oldTab != null) { for (int j = 0; j < oldCap; ++j) {
//Current Node Node Node
<K,V> e;
//Indicates that there is data in the current bucket position, but whether the data is a single data or a linked list or a red-black tree is unknown.
if ((e = oldTab[j]) != null) {
//Recycle memory when jvm GC is convenient oldTab[j]
= null;
//In the first case, there is only one element in the current bucket position and there has never been a collision. This directly calculates where the current element should be stored in the new array and throws it in.
if (e.next == null) newTab[e.hash & (newCap - 1)] = e;
//In the second case, the current node is already treed
else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order
//Third case: the bucket position has formed a chain table

//Low-Bit Chain List: The subscript position of the array stored after expansion, consistent with the subscript position of the current array Node<K,V> loHead = null, loTail = null;
//High-Bit Chain List: The subscript position of the array stored after expansion is: Current array subscript position * Length of the array before expansion Node
<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }


5. get method

(1) get method:

   public V get(Object key) {
        Node<K,V> e;
//Hash when you save it and hash when you remove it
return (e = getNode(hash(key), key)) == null ? null : e.value; }

(2) getNode method:

  final Node<K,V> getNode(int hash, Object key) {
//tab: A Hash list referencing the current hashMap
//first: the head element in the bucket position
//e: Temporary node element
//n:table array length Node
<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
//Case 1: Located bucket elements, the data we want get
if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first;
//Indicates that there is more than one element in the current bucket position, either a chain list or a red-black tree
if ((e = first.next) != null) {
//In the second case, the bucket level has been upgraded, the red and black trees
if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//In the third case, the bucket position forms a chain table
do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }


6. remove method

(1) remove method:

   public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;

(2) removeNode method:

final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
//tab: refers to the Hash list in the current hashMap
//p:Current node element
//n: hash array length
//index: addressing results Node
<K,V>[] tab; Node<K,V> p; int n, index; if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
//Explains that the barrel bits of the route have data and need to be lookup and deleted
//node: results found
//e: Next element of the current node Node
<K,V> node = null, e; K k; V v;
//First case: the element in the current bucket position is the element to be deleted
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) node = p; else if ((e = p.next) != null) {
//Indicates that the current bucket position is either a chain list or a red-black tree
if (p instanceof TreeNode)
//Determine if the current bucket position has been upgraded to a red-black tree node
= ((TreeNode<K,V>)p).getTreeNode(hash, key); else {
//Lookup of Chain List
do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; } p = e; } while ((e = e.next) != null); } }
//Determine node, if not empty, to find elements that need to be deleted by key
if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) {
//In the first case, a node is a tree node, indicating that tree node removal is required
if (node instanceof TreeNode) ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
//In the second case, the barrel element is the result of the search, moving the next element of the element to the barrel position
else if (node == p) tab[index] = node.next; else
//Third, set the next element of the current element p to the next element of the element to be deleted
p.next = node.next; ++modCount; --size; afterNodeRemoval(node); return node; } } return null; }


7. repalce method

   public V replace(K key, V value) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            return oldValue;
        return null;

Keywords: Java less jvm

Added by defect on Thu, 04 Jun 2020 07:52:52 +0300