1. Introduction

Any underlying framework is essentially a collection of data structures, as is HashMap, which is stored in the form of key/value. The underlying framework is stored based on arrays, linked lists, and red-black trees.Copy the code

2. Source code analysis

2.1 Constructor code analysisCopy the code
Public HashMap() {this.loadfactor = DEFAULT_LOAD_FACTOR; this.loadfactor = DEFAULT_LOAD_FACTOR; }Copy the code
2.2 Adding values to the HashMapCopy the code
Public V put(K key, V value) {// Calculate Hash value return putVal(Hash (key), key, value, false, true); }Copy the code
2.3 Enter the code of putVal and take a look at the stored one firstCopy the code
Final V putVal(int hash, K key, V value, Boolean onlyIfAbsent, Boolean evict) {//HashMap True data store Node<K,V>[] TAB; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; 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 { for (int binCount = 0; ; ++binCount) { 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 (e.hash == hash && ((k = e.key) == key || (key ! = null && key.equals(k)))) break; p = e; } } if (e ! = null) { // existing mapping for key V oldValue = e.value; if (! onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }Copy the code