Java source Map source code analysis, map source code analysis
Map is a key-Value Pair and a common data structure. The Map interface defines the basic map behavior, including the core get and put operations. For the definition methods of this interface, see:
JDK has different map implementations for different application scenarios, such as thread-safe hashTable and non-thread-safe hashMap.
For example, a subclass UML class diagram of the map interface in JDK, which has a special case, Dictionary is not recommended:
The methods in the Map interface need to be concerned with get, put, and iterator-related methods such as entrySet (), keySet (), and values.
Entry
Before analyzing map, first understand the storage of elements in map. We know that map can be considered as a set of key-value pairs. in java, map uses Entry to store key-value pairs. This is an interface, its definition is as follows, which is simple and clear. The interface method is mainly to operate on keys and values.
interface Entry<K,V> { K getKey(); V getValue(); V setValue(V value); boolean equals(Object o); int hashCode(); }
AbstractMap
For the abstract Implementation of the Map interface, see the following sample implementation code:
Map <String, String> a =/*** abstract map implementation diagram. According to the document, it is similar to the list interface. ** There are two types of map: mutable and immutable. Immutable only requires the entrySet method, and the returned set iterator does not support modification. ** The put method needs to be implemented for a variable map, and the entrySet iterator also needs to support the modification operation. ** the map outline is implemented in AbstractMap, but its efficiency is hard to say, for example, the method entrySet is used in the get method. ** Generally, child classes are overwritten in a more efficient way. For example, hashMap overwrites keySet, values, and get methods. */new AbstractMap <String, String> () {/** returns the element set in map. The returned set generally inherits AbstractSet. * // @ Override public Set <Map. entry <String, String> entrySet () {return new AbstractSet <Map. entry <String, String> () {@ Override public Iterator <java. util. map. entry <String, String> iterator () {return null ;}@ Override public int size () {return 0 ;};}/ ** throws an exception by default, variable map needs to implement this method */@ Override public String put (String key, String value) {return null ;}};
HashMap
HashMap inherits abstractMap and is a commonly used data structure. It uses hash to insert and obtain data within the time complexity of O (1. The basic implementation can be used to analyze the abstract methods in the previous section.
The implementation and performance analysis of HashMap have provided detailed descriptions of hashMap implementation, put and get operations. Here we will not go into details. The key is the implementation of its iterator. Here we only analyze the entrySet () method, and the implementation of the keySet () and values () methods is in the same line.
For more information about the iterator, see the following source code and related notes:
/*** Returns all the key-value pairs in the map for Traversing */public Set <Map. entry <K, V> entrySet () {return entrySet0 ();}/*** delayed initialization, which is built only when used. ** The values () and keySet () methods also use a similar mechanism */private Set <Map. entry <K, V> entrySet0 () {Set <Map. entry <K, V> es = entrySet; return es! = Null? Es: (entrySet = new EntrySet ();}/*** real enterySet is an internal class, and its key implementation is the implementation of the iterator. ** The values () and keySet () methods also correspond to the corresponding internal classes. * Implement the corresponding iterator. The key lies in this iterator **/private final class EntrySet extends actset <Map. entry <K, V >>{ public Iterator <Map. entry <K, V> iterator () {return newEntryIterator ();} public boolean contains (Object o) {if (! (O instanceof Map. entry) return false; Map. entry <K, V> e = (Map. entry <K, V>) o; Entry <K, V> candidate = getEntry (e. getKey (); return candidate! = Null & candidate. equals (e);} public boolean remove (Object o) {return removeMapping (o )! = Null;} public int size () {return size;} public void clear () {HashMap. this. clear () ;}}/*** entrySet iterator that inherits HashIterator and implements the next method. * The values () and keySet () Methods inherit HashIterator, but the method for implementing next is different. ** you can compare them. ** The key lies in HashIterator ***/private final class EntryIterator extends HashIterator <Map. entry <K, V >>{ public Map. entry <K, V> next () {return nextEntry () ;}}/***** keySet () corresponding iterator */private final class KeyIterator extends HashIterator <K> {public K next () {return nextEntry (). getKey () ;}/ *** hashmap entrySet () keySet () values () Universal iterator */private abstract class HashIterator <E> implements Iterat Or <E> {Entry <K, V> next; // next entry to return int expectedModCount; // For fast-fail int index; // current slot Entry <K, v> current; // current entry HashIterator () {expectedModCount = modCount; if (size> 0) {// advance to first entry [] t = table; // during construction, find the first non-null array element in the array, that is, the Entry linked list. For the implementation of hashmap, see // my previous blog post while (index <t. length & (next = t [index ++]) = null) ;}} public final bool Ean hasNext () {return next! = Null;}/*** key implementation, which is easy to understand. When searching for next, it is the same as when constructing the iterator */final Entry <K, V> nextEntry () {if (modCount! = ExpectedModCount) throw new ConcurrentModificationException (); Entry <K, V> e = next; if (e = null) throw new NoSuchElementException (); if (next = e. next) = null) {Entry [] t = table; while (index <t. length & (next = t [index ++]) = null);} current = e; return e;} public void remove () {if (current = null) throw new IllegalStateException (); if (modCount! = ExpectedModCount) throw new ConcurrentModificationException (); Object k = current. key; current = null; HashMap. this. removeEntryForKey (k); expectedModCount = modCount ;}}
HashTable
The implementation is basically the same as that of hashMap, but the synchronization operation is added to the method. It can be used in a multi-threaded environment. But now there is ConcurrentHashMap. In high concurrency, you can use it to replace hashtable.
LinkedHashMap
HashMap may not meet the requirements in some scenarios, because the elements in it are unordered. LinkedHashMap solves this problem to some extent.
It inherits HashMap in implementation, extends haspMap. enteySet in storage, adds the before and after fields, and connects the elements of hashMap with a two-way linked list. This two-way linked list determines its traversal order. The order is usually the order in which the map is inserted. However, when the value of accessOrder is true, the traversal order will be LRU.
To study its orderliness, we can start with the put method, get method, and Traversal method. First, let's look at the get method:
/*** Call the getEntry method of the parent class directly. The key lies in * e. code for recordAccess (this) */public V get (Object key) {Entry <K, V> e = (Entry <K, V>) getEntry (key ); if (e = null) return null; e. recordAccess (this); return e. value;}/*** Entry. recordAccess method ** if it is the access order (accessOrder = true), put it in the next position of the header node * Otherwise, nothing will be done. * This way, according to the initial accessOrder attribute, to determine the order of traversal. */Void recordAccess (HashMap <K, V> m) {LinkedHashMap <K, V> lm = (LinkedHashMap <K, V>) m; if (lm. accessOrder) {lm. modCount ++; remove (); addBefore (lm. header );}}
Put method:
/*** The put method calls this method, which overwrites the implementation in the parent class. */void addEntry (int hash, K key, V value, int bucketIndex) {createEntry (hash, key, value, bucketIndex); // Remove eldest entry if your ucted, else grow capacity if appropriate Entry <K, V> eldest = header. after; // callback. If it is necessary to remove the old elements, the latest elements are at the end of the linked list. If (removeEldestEntry (eldest) {removeEntryForKey (eldest. key);} else {if (size> = threshold) resize (2 * table. length) ;}}/*****/void createEntry (int hash, K key, V value, int bucketIndex) {HashMap. entry <K, V> old = table [bucketIndex]; Entry <K, V> e = new Entry <K, V> (hash, key, value, old ); table [bucketIndex] = e; // The essence is to insert the end e of the two-way linked list. addBefore (header); size ++;}/*** is inserted before the existingEntry because it is a two-way linked list. When the existingEntry is the header, * is inserted to the end of the linked list. **/Private void addBefore (Entry <K, V> existingEntry) {after = existingEntry; before = existingEntry. before; before. after = this; after. before = this ;}
The traversal iteration directly uses the bidirectional linked list to carry out the iteration interface, which is not described here. The source code is easy to understand. Note that listing overwrites the method for generating the iterator in the parent class.
Both TreeMap and CurrentHashMap can be analyzed in a separate article. Here is a simple example. TreeMap is based on B-tree map and is sorted by key. CurrentHashMap is a powerful class in concurrent sending and writing. It is suitable for reading and writing data in multi-thread high concurrency.