HashMap source code analysis, hashmap source code

Source: Internet
Author: User

HashMap source code analysis, hashmap source code

The JDK version I use is 1.8.0 _ 144.

HashMap is a common data structure that operates in the form of key-value pairs.

Source code analysis:

// Default initial capacity static final int DEFAULT_INITIAL_CAPACITY = 1 <4; // default maximum capacity static final int MAXIMUM_CAPACITY = 1 <30; // default loading factor, static final float DEFAULT_LOAD_FACTOR = 0.75f; // actually used Hash table transient Node <K, V> [] table; // HashMap size, that is, the number of key-value pairs stored in HashMap transient int size; // the threshold value of the key-value pair, used to determine whether the hash table capacity int threshold needs to be expanded; // The loading Factor final float loadFactor; // number of modifications, used for fail-fast mechanism transient int modCount;

The structure of a hash table is as follows. The structure is a common linked list structure, which has the following attributes: hash value, key value, value, and object of the next value in the next linked list:

 /**     * Basic hash bin node, used for most entries.  (See below for     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)     */    static class Node<K,V> implements Map.Entry<K,V> {        final int hash;        final K key;        V value;        Node<K,V> next;        Node(int hash, K key, V value, Node<K,V> next) {            this.hash = hash;            this.key = key;            this.value = value;            this.next = next;        }        public final K getKey()        { return key; }        public final V getValue()      { return value; }        public final String toString() { return key + "=" + value; }        public final int hashCode() {            return Objects.hashCode(key) ^ Objects.hashCode(value);        }        public final V setValue(V newValue) {            V oldValue = value;            value = newValue;            return oldValue;        }        public final boolean equals(Object o) {            if (o == this)                return true;            if (o instanceof Map.Entry) {                Map.Entry<?,?> e = (Map.Entry<?,?>)o;                if (Objects.equals(key, e.getKey()) &&                    Objects.equals(value, e.getValue()))                    return true;            }            return false;        }    }

The HashMap constructor is as follows. All constructor functions directly or indirectly implement the following main constructor functions:

Public HashMap (int initialCapacity, float loadFactor) {// empty if (initialCapacity <0) throw new IllegalArgumentException ("Illegal initial capacity:" + initialCapacity) for the initial capacity of HashMap ); // The initial capacity of HashMap cannot exceed the maximum capacity. if (initialCapacity> MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; // The loading factor. The default value is 0.75f if (loadFactor <= 0 | Float. isNaN (loadFactor) throw new IllegalArgumentException ("Illegal load factor:" + loadFactor); // initialize the loading factor this. loadFactor = loadFactor; // initialization threshold this. threshold = tableSizeFor (initialCapacity );}

HashMap Storage Method

Public V put (K key, V value ){
// Call the storage function
Return putVal (hash (key), key, value, false, true );

}
Final V putVal (int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {// carries the current hash table
Node <K, V> [] tab;
// Store the Node variable in the hash table that is calculated based on the hash value
Node <K, V> p;
Int n, I;
// Initialize the tab to the current hash table and empty it. if the current hash table is empty, re-allocate if (tab = table) = null | (n = tab. length) = 0) n = (tab = resize ()). length;
// If the Node in the table that is calculated based on the hash value and table length is null, a Node is created, and store the subscript in the hash table if (p = tab [I = (n-1) & hash]) = null) tab [I] = newNode (hash, key, value, null); else {// otherwise, the value of the Node is not empty // store the hash value of the subobject
Node <K, V> e;
// Key value
K k;
// If the hash value of Node is the same as that of the saved hash, the Node variable in the current table is assigned as e if (p. hash = hash & (k = p. key) = key | (key! = Null & key. equals (k) e = p; else if (p instanceof TreeNode) // if the Node value type is TreeNode
E = (TreeNode <K, V>) p ). putTreeVal (this, tab, hash, key, value); else {// otherwise, the loop query for (int binCount = 0; ++ binCount ){
// Query from the next Node value. If it is null, a Node is created and connected to the next Node of the Node.
If (e = p. next) = null) {p. next = newNode (hash, key, value, null); if (binCount> = TREEIFY_THRESHOLD-1) //-1 for 1st treeifyBin (tab, hash); break ;}
// If the storage is successful, the hash value of e should be the same as that of hash if (e. hash = hash & (k = e. key) = key | (key! = Null & key. equals (k) break; p = e; // cyclically traverse next of p, p = e is p = p. next }}
// If e is not empty, the data if (e! = Null) {// existing mapping for key // retrieve old data
V oldValue = e. value;
// Store new data
If (! OnlyIfAbsent | oldValue = null) e. value = value; // The Time-Space Method of this method
AfterNodeAccess (e );
// Return old data
Return oldValue ;}}+ modCount; // execution times + + if (++ size> threshold) // if the number of data in the table is + 1, if the number of data in the table exceeds the threshold, then, the table resize (); afterNodeInsertion (evict); return null;} is re-allocated ;}

Data Retrieval (similar to stored data ):

    public V get(Object key) {        Node<K,V> e;        return (e = getNode(hash(key), key)) == null ? null : e.value;    }final Node<K,V> getNode(int hash, Object key) {        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) {            if (first.hash == hash && // always check first node                ((k = first.key) == key || (key != null && key.equals(k))))                return first;            if ((e = first.next) != null) {                if (first instanceof TreeNode)                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);                do {                    if (e.hash == hash &&                        ((k = e.key) == key || (key != null && key.equals(k))))                        return e;                } while ((e = e.next) != null);            }        }        return null;    }

 

  

  

  

 

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.