Java record-71-HashMap source code analysis

Source: Internet
Author: User

Java record-71-HashMap source code analysis
An array is maintained at the underlying layer of HashMap. The objects we place in HashMap are actually stored in this array. Each element in the array maintains a linked list, and the hash values of all elements in each linked list are the same. HashMap's four constructor methods: the underlying maintained array Entry [] table. The default size of the array is 16 and is an integer power of 2. The Entry object stored in the underlying array, is an internal class of HashMap, including the key, value, and next variables;

   /**    * The table, resized as necessary. Length MUST Always be a power of two.    */   transient Entry[] table;   static class Entry<K,V> implements Map.Entry<K,V> {        final K key;        V value;        Entry<K,V> next;        final int hash;        ......    }        public HashMap(int initialCapacity, float loadFactor) {        if (initialCapacity < 0)            throw new IllegalArgumentException("Illegal initial capacity: " +                                               initialCapacity);        if (initialCapacity > MAXIMUM_CAPACITY)            initialCapacity = MAXIMUM_CAPACITY;        if (loadFactor <= 0 || Float.isNaN(loadFactor))            throw new IllegalArgumentException("Illegal load factor: " +                                               loadFactor);        // Find a power of 2 >= initialCapacity        int capacity = 1;        while (capacity < initialCapacity)            capacity <<= 1;        this.loadFactor = loadFactor;        threshold = (int)(capacity * loadFactor);        table = new Entry[capacity];        init();    }    public HashMap(int initialCapacity) {        this(initialCapacity, DEFAULT_LOAD_FACTOR);    }    public HashMap() {        this.loadFactor = DEFAULT_LOAD_FACTOR;        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);        table = new Entry[DEFAULT_INITIAL_CAPACITY];        init();    }    public HashMap(Map<? extends K, ? extends V> m) {        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);        putAllForCreate(m);    }

 

Put: When the added key is null, the first element of the table is taken out, find the key = null element in the linked list led by this element. If yes, replace it with the key. If no key is set, add it. If the key is not null, calculate the hash value of the key, call a function to calculate an integer based on experience. Then, calculate the position of the newly added element in the array based on the calculated hash value and the length of the array table; retrieve the element value of the position calculated above from the underlying array, that is, the Entry object, and find the object with the same key from the linked list led by this object. If yes, replace it with the element value; if no equal object is found in the previous step, add a new object. Add the object to the table of the number of layers. The position is the position value calculated above, and point the object next to the elements previously stored in the location;
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;    }    private V putForNullKey(V value) {        for (Entry<K,V> e = table[0]; e != null; e = e.next) {            if (e.key == null) {                V oldValue = e.value;                e.value = value;                e.recordAccess(this);                return oldValue;            }        }        modCount++;        addEntry(0, null, value, 0);        return null;    }    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);    }    static int indexFor(int h, int length) {        return h & (length-1);    }    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);    }

 

All the elements in the set are used for reading. Let's take a look at the elements: special processing is required when the get method key is null, return the value of key = null from the first element of the underlying array table. If the key is not null, calculate the hash value of the key, obtain an element based on the value in the table, and then find the value of the corresponding key in the linked list where the element is located;
    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;    }    private V getForNullKey() {        for (Entry<K,V> e = table[0]; e != null; e = e.next) {            if (e.key == null)                return e.value;        }        return null;    }

 

Common methods include: containsKey, remove, keySet, entrySet, and values. These methods need to be searched in the underlying array and then traverse the corresponding linked list. According to the set threshold value, but when the threshold value is reached, the underlying array of HashMap will be expanded. Why is the newly added object added to the chain's header instead of its tail? In order to improve the performance, the operating system has such a principle that the probability of next access to the latest elements added to the chain is greater than the previous one. Therefore, the elements added to the chain table header are, if this element is accessed for the next time, the first access is available. If it is placed at the end, the entire linked list of variables is needed to find the element. The process of adding an object in HashMap: when a key pair is put to HashMap, it calculates a location based on the hashCode value of the key, this location is where the object is to be stored in the array. If no object exists at this position, the object is directly put into the array. If an object already exists at this position, search for the existing object chain (the Entry class has a next member variable of the Entry type pointing to the next object of the object). If there is an object in the chain, then use the equals Method for comparison. If the key of an object on the chain is true, the object already exists and the old object will be replaced with the new object; if the equals method of all objects on the chain is false, put the object into the array, and then link the object that existed before the position in the array to the end of the object.

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.