Java Collection framework 07-Map architecture and source code analysis
In the previous sections, we analyzed the Collection and the List part in the Collection, and there is a Set in the Collection. Since the Set is implemented based on Map, we will analyze the Map first, next, we will continue to learn about Set. First, let's take a look at the Map architecture diagram:
We can see that:
1. Map is an interface, and the content stored in Map isKey-value Pair).
2. For convenience, we abstract the AbstractMap class to inherit other classes. This class implements most of the APIs in Map. The specific implementation of other maps can be directly inherited by the AbatractMap class.
3. SortedMap is also an interface that inherits from the Map interface. The difference between content in SortedMap and Map is that it isOrdered key-value pairsThe sorting method is implemented by the Comparator.
4. navigableMap is also an interface that inherits from SortedMap, so it must be ordered. In addition, NavigableMap has some navigation methods: for example, obtain "key-value pairs greater than or equal to an object.
5. Further down is the specific implementation class. TreeMap inherits from AbstractMap and implements the NavigableMap interface. Therefore,The content in TreeMap is an ordered key-value pair..
6. HashMap only inherits AbstractMap and does not implement the NavigableMap interface. Therefore,The content of HashMap is only a key-Value Pair and is not necessarily ordered..
7. WeakHashMap only inherits AbstractMap. The difference between it and HashMap is that the key type is different,The WeakHashMap key is a weak key..
8. Although HashTable does not inherit from AbstractMap, It inherits from Dictionary (Dictionary is also the key-value pair interface) and implements the Map interface. Therefore,The HashTable content is also a key-Value Pair and does not guarantee the order.. However, compared with HashMap,HashTable is thread-safe.And supports traversing through Enumeration.
This section mainly discusses the Map architecture, introduces various interfaces and abstract classes, and studies some source code. For the source code of specific implementation classes such as TreeMap and HashMap, we will conduct a detailed study in subsequent chapters.
1. Map
The definition and API of Map are as follows:
Package java. util; public interface Map
{Boolean isEmpty (); boolean containsKey (Object key); boolean containsValue (Object value); V get (Object key); V put (K key, V value ); V remove (Object key); void putAll (Map
M); void clear (); Set
KeySet (); // Set Collection for saving the key
Values (); // Save the Collection Set of value
> EntrySet (); // Save the Set interface Entry of Map. Entry.
{// An interface inside Map. The Entry encapsulates key and value information K getKey (); V getValue (); V setValue (V value ); boolean equals (Object o); int hashCode () ;}boolean equals (Object o); int hashCode ();}
We can see from the source code above:
1. Map provides some interfaces for returning the key set, value set, and key-value ing relationship set.
KeySet () is the Set used for the Return key;
Values () is a Set of returned values;
EntrySet () is used to return the Set of the key-value Set. The key-value information is encapsulated in the Entry.
2. Map also provides methods such as "get key", "Get value based on key", and "whether a key or value is included.
3. Map. Entry is an interface inside Map, and Map. Entry is a key-value pair. To obtain the key-Value Pair in Map,You can use Map. entrySet () to obtain a set containing Map. Entry.Then, you can use this Entry to perform key-value operations.
2. AbstractMap
AbstractMap inherits Map, but does not implement the entrySet () method (this method is still abstract modification). To Inherit AbstractMap, You need to implement the entrySet () method by yourself. The put (Kkey, V value) method is not actually implemented. "no real implementation" means that the method has been implemented in the form, that is, it has not been modified in abstract, however, the method only throws an exception and does not actually implement the method body content. We can see from the source code below.
Package java. util; import java. util. Map. Entry; public abstract class implements actmap
Implements Map
{// Empty constructor protected AbstractMap () {}// returns the number of key-value pairs stored in Map public int size () {return entrySet (). size () ;}// determine whether Map is empty public boolean isEmpty () {return size () = 0 ;} // determine whether a Map contains a public boolean containsValue (Object value) {// entrySet () and returns a Map containing the value. entry
And then obtain the Set iterator Iterator.
> I = entrySet (). iterator (); if (value = null) {// here we can see that value = null while (I. hasNext () {Entry
E = I. next (); if (e. getValue () = null) return true ;}} else {while (I. hasNext () {Entry
E = I. next (); if (value. equals (e. getValue () return true;} return false;} // checks whether the Map contains a public boolean containsKey (Object key) {Iterator
> I = entrySet (). iterator (); if (key = null) {// from here we can see that key = null while (I. hasNext () {Entry
E = I. next (); if (e. getKey () = null) return true ;}} else {while (I. hasNext () {Entry
E = I. next (); if (key. equals (e. getKey () return true;} return false;} // obtain the corresponding value through the key public V get (Object key) {Iterator
> I = entrySet (). iterator (); if (key = null) {while (I. hasNext () {Entry
E = I. next (); if (e. getKey () = null) // from here, we can see that key = null must value = null return e. getValue () ;}} else {while (I. hasNext () {Entry
E = I. next (); if (key. equals (e. getKey () return e. getValue () ;}return null;} public V put (K key, V value) {// There is no specific implementation in the put method body, you must implement throw new UnsupportedOperationException ();} // Delete the Entry public V remove (Object key) {Iterator of the specified key.
> I = entrySet (). iterator (); Entry
CorrectEntry = null; // used to save the Entry to be deleted if (key = null) {while (correctEntry = null & I. hasNext () {Entry
E = I. next (); if (e. getKey () = null) correctEntry = e ;}} else {while (correctEntry = null & I. hasNext () {Entry
E = I. next (); if (key. equals (e. getKey () correctEntry = e ;}} V oldValue = null; // used to save the value of the Entry to be deleted if (correctEntry! = Null) {// If correctEntry is not null, the Entry oldValue = correctEntry to be deleted is found. getValue (); I. remove ();} return oldValue;} // Add a new Map m public void putAll (Map
M) {for (Map. Entry
E: m. entrySet () put (e. getKey (), e. getValue (); // call the put method not implemented above} // clear the entire Map public void clear () {entrySet (). clear () ;}// keySet is used to save the key's Set, and values is used to save the value's Collection transient volatile Set
KeySet = null; transient volatile Collection
Values = null; // obtain all the keys in the Map and save them to the keySet member variable. KeySet is a Set
Public Set
KeySet () {if (keySet = null) {keySet = new AbstractSet
() {// Internal class AbstractSet
Public Iterator
Iterator () {return new Iterator
() {// Internal class Iterator
Private Iterator
> I = entrySet (). iterator (); public boolean hasNext () {return I. hasNext ();} public K next () {return I. next (). getKey ();} public void remove () {I. remove () ;};} public int size () {return AbstractMap. this. size ();} public boolean isEmpty () {return AbstractMap. this. isEmpty ();} public void clear () {AbstractMap. this. clear ();} public boolean contains (Object k) {return AbstractMap. this. contain SKey (k) ;}};} return keySet ;}// obtain all values in the Map and save them to the values member variable to return them. Values is a Collection.
Public Collection
Values () {if (values = null) {values = new AbstractCollection
() {Public Iterator
Iterator () {return new Iterator
() {Private Iterator
> I = entrySet (). iterator (); public boolean hasNext () {return I. hasNext ();} public V next () {return I. next (). getValue ();} public void remove () {I. remove () ;};} public int size () {return AbstractMap. this. size ();} public boolean isEmpty () {return AbstractMap. this. isEmpty ();} public void clear () {AbstractMap. this. clear ();} public boolean contains (Object v) {return AbstractMap. this. containsValue (v) ;}}}return values;} public abstract Set
> EntrySet (); // not implemented, or the equals method in the abstract method // Map. It can be seen from the source code that the value is compared, true public boolean equals (Object o) {if (o = this) is returned only when all values are equal. // if all objects are the same, true return true is returned. if (! (O instanceof Map) // If the input object is not of the Map type, it must be false, return false; Map
M = (Map
) O; if (m. size ()! = Size () // the size of the two objects must be different; false return false; try {// Well, the above conditions are met, and the Iterator value is compared below
> I = entrySet (). iterator (); while (I. hasNext () {Entry
E = I. next (); K key = e. getKey (); V value = e. getValue (); if (value = null) {if (! (M. get (key) = null & m. containsKey (key) return false;} else {if (! Value. equals (m. get (key) return false ;}} catch (ClassCastException unused) {return false;} catch (NullPointerException unused) {return false;} return true ;} // hashCode public int hashCode () {int h = 0; Iterator
> I = entrySet (). iterator (); while (I. hasNext () h + = I. next (). hashCode (); // call the return h of the hashCode () method in the Entry;} // outputs public String toString () {Iterator in the form of {key = value}
> I = entrySet (). iterator (); if (! I. hasNext () return "{}"; StringBuilder sb = new StringBuilder (); // use StringBuilder sb. append ('{'); for (;) {Entry
E = I. next (); K key = e. getKey (); V value = e. getValue (); sb. append (key = this? "(This Map)": key); sb. append ('='); sb. append (value = this? "(This Map)": value); if (! I. hasNext () return sb. append ('}'). toString (); sb. append (','). append ('') ;}} protected Object clone () throws CloneNotSupportedException {AbstractMap
Result = (AbstractMap
) Super. clone (); result. keySet = null; result. values = null; return result;} private static boolean eq (Object o1, Object o2) {return o1 = null? O2 = null: o1.equals (o2);} // SimpleEntry implements the Entry interface in the Map class and the Serializable interface to serialize public static class SimpleEntry
Implements Entry
, Java. io. serializable {private static final long serialVersionUID =-8499721149061103585L; private final K key; private V value; public SimpleEntry (K key, V value) {this. key = key; this. value = value;} public SimpleEntry (Entry
Entry) {this. key = entry. getKey (); this. value = entry. getValue () ;}public K getKey () {return key;} public V getValue () {return value;} public V setValue (V value) {V oldValue = this. value; this. value = value; return oldValue;} public boolean equals (Object o) {if (! (O instanceof Map. entry) return false; Map. entry e = (Map. entry) o; return eq (key, e. getKey () & eq (value, e. getValue ();} public int hashCode () {return (key = null? 0: key. hashCode () ^ (value = null? 0: value. hashCode ();} public String toString () {return key + "=" + value ;}// SimpleImmutableEntry implements the Entry interface in the Map class, the Serializable interface is also implemented to serialize public static class SimpleImmutableEntry
Implements Entry
, Java. io. serializable {private static final long serialVersionUID = 7138329143949025153L; private final K key; private final V value; public SimpleImmutableEntry (K key, V value) {this. key = key; this. value = value;} public SimpleImmutableEntry (Entry
Entry) {this. key = entry. getKey (); this. value = entry. getValue () ;}public K getKey () {return key;} public V getValue () {return value;} public V setValue (V value) {throw new UnsupportedOperationException ();} public boolean equals (Object o) {if (! (O instanceof Map. entry) return false; Map. entry e = (Map. entry) o; return eq (key, e. getKey () & eq (value, e. getValue ();} public int hashCode () {return (key = null? 0: key. hashCode () ^ (value = null? 0: value. hashCode ();} // rewrite the toString method. return the public String toString () {return key + "=" + value;} in the form of key = value ;}}}
From the source code, we can see that the AbstractMap class provides the main implementation of the Map interface to minimize the work required to implement this interface, but AbstractMap does not implement the entrySet () method. So if we want to implement unmodifiable Map, we only need to extend this class and provide the entrySet () method. In addition, we can also see from the source code that entrySet () the Set (I .e. keySet) returned by the method does not support the add () or remove () method. If we want to implement a modifiable Map, we must overwrite the put () method. Otherwise, UnsupportedOperationException will be thrown and entrySet. the iterator I returned by iterator () must also implement its remove method.
However, we generally do not need to implement Map by ourselves, because we already have Map implementation classes, such as HashMap and TreeMap.
3. SortedMap
SortedMap is also an interface that inherits from the Map interface. Sorted indicates that it is an ordered key-value ing.
SortedMap has two sorting methods: Natural sorting and specified comparator sorting. All elements that insert an ordered SortedMap must implement the Comparable interface (or accepted by the specified comparator ).
SortedMap APIs:
// APIs inherited from Map are no longer written into package java. util; public interface SortedMap
Extends Map
{Comparator
Comparator (); // returns the comparator object SortedMap
SubMap (K fromKey, K toKey); // return Map SortedMap within the specified key range
HeadMap (K toKey); // returns SortedMap, a collection smaller than the specified key.
TailMap (K fromKey); // return K firstKey (), a collection greater than or equal to the specified key; // return the key K lastKey () of the first element (); // return the key of the last element}
4. NavigableMap
NavigableMap inheritance and SortedMap, first look at its API
package java.util;public interface NavigableMap
extends SortedMap
{ Map.Entry
lowerEntry(K key); K lowerKey(K key); Map.Entry
floorEntry(K key); K floorKey(K key); Map.Entry
ceilingEntry(K key); K ceilingKey(K key); Map.Entry
higherEntry(K key); K higherKey(K key); Map.Entry
lastEntry(); Map.Entry
pollLastEntry(); NavigableMap
descendingMap(); NavigableSet
navigableKeySet(); NavigableSet
descendingKeySet(); NavigableMap
subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive); NavigableMap
headMap(K toKey, boolean inclusive); NavigableMap
tailMap(K fromKey, boolean inclusive); SortedMap
subMap(K fromKey, K toKey); SortedMap
headMap(K toKey); SortedMap
tailMap(K fromKey);}
As shown in the API, NavigableMap not only inherits the features of SortedMap, but also provides the following functions:
1. the lowerEntry, floorEntry, cellingEntry, and higherEntry methods provide the Map associated with keys smaller than, less than or equal to, greater than or equal to, and greater than the given key. entry object.
2. Operation key methods are provided: The lowerKey, floorKey, cellingKey, and higherKey Methods return keys smaller than, less than or equal to, greater than or equal to, and greater than the given key.
3. Obtain a subset of key-value pairs.
5. Dictionary
Dictionary also includes the basic method for operating a key-value pair. Its definition and API are as follows:
package java.util;public abstractclass Dictionary
{ public Dictionary() { } abstract public int size(); abstract public boolean isEmpty(); abstract public Enumeration
keys(); abstract public Enumeration
elements(); abstract public V get(Object key); abstract public V put(K key, V value); abstract public V remove(Object key);}