The previous discussion of HashMap and Hashtable source code, this section we will discuss the treemap. First grasp the treemap from the whole, then analyze its source code, in-depth analysis of the implementation of TreeMap.
1. TreeMap Introduction
TreeMap is an ordered set of Key-value, which is built through the red-black tree, if the red-black trees do not understand, please refer to this blog post: red-black tree. Let's take a look at the inheritance relationship of TreeMap:
Java.lang.Object ? Java.util.abstractmap<k, v> ? Java.util.treemap<k, V>public class treemap<k,v> extends Abstractmap<k,v> implements Navigablemap<k,v>, cloneable, java.io.Serializable {}
As can be seen from the inheritance relationship, TreeMap inherits and Abstractmap, implements the Navigablemap interface, which means that it supports a series of navigation methods, such as returning an ordered key collection. It also implements the Cloneable interface, which means it can be cloned. The serializable interface is also implemented to indicate that it supports serialization.
TreeMap is based on a red-black tree, which is sorted according to the natural order of its key, or sorted according to the Comarator provided by the user when creating the mapping, andTreeMap is non-synchronous .
Let's take a look at what APIs treemap has:
Entry<k, v> ceilingentry (k key) K Ceilingkey (k key) void Clear () Object clone () comparator<? Super K> Comparator () Boolean containskey (Object key) navigableset<k> Descending KeySet () navigablemap<k, v> descendingmap () set<entry<k, v>> entryset () entry<k, V> Firstentry () k Firstkey () entry<k, v> floorentry (k key) K Floorkey (k key) V get (Object key) navigablemap<k, V> Headmap (k to , Boolean inclusive) sortedmap<k, v> Headmap (k toexclusive) entry<k, v> Higherentry (k Key) K Higherkey (k key) Boolean isEmpty () set<k> KeySet () entry<k, v> lastentry () K Lastkey () entry&Lt K, v> lowerentry (k key) K Lowerkey (k key) navigableset<k> Naviga Blekeyset () entry<k, v> pollfirstentry () entry<k, v> polllastentry () V Put (K key, v value) v Remove (Object key) int size () sortedmap< ; K, v> SubMap (k frominclusive, K toexclusive) navigablemap<k, v> SubMap (K from, Boolean FROMINCL Usive, K to, Boolean toinclusive) navigablemap<k, v> Tailmap (k from, Boolean inclusive) sortedmap<k, v> Tailmap (K frominclusive)
As you can see from these APIs, there are a total of these categories: entry-related, key-related, and map-related, as well as keyset and EntrySet, which are discussed in detail below.
2. TreeMap Source Analysis (based on JDK1.7)
2.1 Storage Structure
Since TreeMap is based on a red-black tree, it maintains a red-Haishi data structure internally, and each key-value pair is also stored in a entry, except that entry is different from HashMap in front hashtable or entry, TreeMap's entry is actually a node of red-Haishi. Let's take a look at the entry definition in TreeMap:
private transient entry<k,v> root = null;
Then let's look at the implementation of the entry entity class:2.2 Entry entity classes and related methods
look at the entry entity class first:
Private static Final Boolean red = False;private static final Boolean BLACK = true;//is a node of a red-black tree static final cl Entry<k,v> implements map.entry<k,v> { k key; v value; Entry<K,V> left = null; Left Dial hand node Entry<K,V> right = null; Right child node Entry<K,V> parent; Parent node boolean color = BLACK; Tree color, default to Black entry (K key, V value, entry<k,v> parent) {//Construction method & Nbsp;this.key = key; this.value = value; This.parent = parent; } public K GetKey () {//Get key & Nbsp;return key; } public V getValue () {//Get value & Nbsp;return value; } public v setValue (v value) {//Set VALUE&Nbsp; v oldValue = this.value; this.value = value;& nbsp; return oldvalue; } public boolean equals ( Object o) {//key and value are equal before returning true if (! o instanceof map.entry) return false; Map.Entry<?,? > E = (map.entry<?,? >) o; return Valequals (Key,e.getkey ()) && valequals (Value,e.getvalue ()); } public int Hashcode () {//Calculate hashcode int Keyhash = (key==null? 0:key.hashcode ()); &NBSP;&N Bsp int Valuehash = (value==null? 0:value.hashcode ()); return Keyhash ^ valuehash; } public String ToString () {//override toString method return key + "=" + value; }} As can be seen from the entry entity class, the entry in TreeMap is a node of a red-black tree. There are methods associated with this entry.firstentry (), Lastentry (), Lowerentry (), Higherentry (), Floorentry (), Ceilingentry ()。 They are all similar in principle, we only analyze Firstentry (), others put in the source code analysis:
Public map.entry<k,v> Firstentry () {return exportentry (Getfirstentry ());} Get the first node in the TreeMap (that is, the node with the smallest sort by key), and if TreeMap is empty, return nullfinal entry<k,v> getfirstentry () {entry<k,v> p = root ; if (P! = null) while (p.left! = null) p = p.left; return p;}
The code is simple, keep going down until you find the node and then return. Why not call Getfirtstentry () directly, but provide firstentry () for external calls? This refers to the role of the Exportentry () method, because if the Getfirstentry () method is called directly, the returned entry can be modified, but after the Exportentry () method is wrapped, it cannot be modified, so doing soprevent entry from being used to modify returned。 Let's take a look at how the Exportentry () method wraps the Entry object:
Static <K,V> map.entry<k,v> exportentry (treemap.entry<k,v> e) {return (E = = null)? null:new ABSTRACTMA P.simpleimmutableentry<> (e);}
As we can see, it is implemented by a static class Simpleimmutableentry in the new Abstractmap class, so how is the Simpleimmutableentry class implemented, for convenience, We also take this kind of class (of course, you can see this blog map architecture and source analysis, which is about Abstractmap abstract class source), below to see how this simpleimmutableentry static class is implemented:
public static class Simpleimmutableentry<k,v>implements entry<k,v>, java.io.serializable{private static Final long Serialversionuid = 7138329143949025153l;private final K key;private final V value;public simpleimmutableentry ( K key, V value) {//Initialize the object with key and value This.key = Key;this.value = value;} Public Simpleimmutableentry (entry<? extends K,? extends v> Entry) {//by passing in a Entry initialization object this.key = Entry.getkey (); This.value = Entry.getvalue ();} Public K GetKey () {return key;} Public V GetValue () {return value;} Public v SetValue (v value) {//!!! Key place here, cannot setvalue, otherwise will throw Unsupportedoperationexception exception 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 ());} The ToString method is overridden to return the Key=value form public String toString () {returN key + "=" + Value;}} as can be seen from the above code, the entry is not allowed to be modified content, which is why the TreeMap class does not directly put Getfirstentry ( Method is exposed, but provides the reason for the firstentry () for external invocation. Other similar methods about entry I do not repeat, I put in the source code analysis, are not difficult to understand. As follows:
/*********************** methods related to Entry ******************************///Get the node in the TreeMap key for key final entry<k,v> Getentry (Object key) {//If the comparer is not NULL, getentryusingcomparator to get if (comparator! = NULL) return Getentryusingcomparator (key); if (key = = null) throw new NullPointerException (); comparable<? Super k> K = (comparable<? super K>) key; entry<k,v> p = root; If there is no comparator, normal down while (P! = null) {int CMP = K.compareto (P.key); if (CMP < 0) p = p.left;else if (cmp > 0) p = p.right;e Lsereturn p; Returns}return null if found;} Use the comparator to obtain the entryfinal entry<k,v> getentryusingcomparator (Object key) corresponding to key {k k = (k) key; comparator<? Super K> CPR = comparator;if (CPR = null) {entry<k,v> p = root;while (P! = null) {int CMP = Cpr.compare (K, P.key if (CMP < 0) p = p.left;else if (cmp > 0) p = P.right;elsereturn p;}} return null;} /*--------------------------------------------------------*/public map.entry<k,v> firstentry () {return Exportentry (Getfirstentry ());} //Get the first node in the TreeMap (that is, the node with the smallest sort by key), and if TreeMap is empty, return nullfinal entry<k,v> getfirstentry () {entry<k,v> p = root; if (P! = null) while (p.left! = null) p = P.left;return p;} /*-----------------------------------------------*/public map.entry<k,v> lastentry () {return exportentry ( Getlastentry ());} Get the last node in the TreeMap (the node with the largest sort by key), if TreeMap is empty, return nullfinal entry<k,v> getlastentry () {entry<k,v> p = root; if (P! = null) while (p.right! = null) p = P.right;return p;} /*------------------------------------------------*///pops up the first node, that is, delete public map.entry<k,v> pollfirstentry () { Entry<k,v> p = getfirstentry (); map.entry<k,v> result = Exportentry (P); if (P! = null) deleteentry (p); return result;} pops up the last node, that is, delete public map.entry<k,v> polllastentry () {entry<k,v> p = getlastentry (); map.entry<k,v> result = Exportentry (P); if (P! = null) deleteentry (p); return result;} /*-------------------------------------------------*/public map.entry<k,v> floorentry (K key) {RETUrn Exportentry (getfloorentry (key));} Public map.entry<k,v> ceilingentry (K key) {return Exportentry (Getceilingentry (key));} Gets the smallest node that is not less than key in TreeMap,//If it does not exist (that is, all nodes in TreeMap are larger than key), return nullfinal entry<k,v> getceilingentry (K key) {Entry <K,V> p = root;while (P! = null) {int CMP = compare (key, P.key); if (CMP < 0) {//Case 1. If P.key > Keyif (p.left!) = null)//if p has left dial hand node p = p.left; Go down to the left Elsereturn p; Otherwise return p} else if (cmp > 0) {//Case 2:p.key < Keyif (p.right! = null) {p = p.right;} else {//if p does not exist right child, then find the successor node of P and return to Note: the "successor of P" returned here has 2 possibilities: First, NULL, and second, the smallest node in TreeMap greater than key. The core of this understanding is that Getceilingentry is traversed from root. If Getceilingentry can get to this step, then it's "key of the node that has been traversed" > key. To understand the above, it is easy to understand why "the successor of P" is another 2 possibilities. entry<k,v> parent = p.parent; entry<k,v> ch = p;while (parent! = NULL && ch = = parent.right) {ch = parent;parent = parent.parent;} return parent;}} else//Case 3:p.key = Keyreturn p;} return null;} Gets the largest node in the TreeMap that is not larger than key;//If it does not exist (that is, all nodes in the treemap are smaller than key),The principle of returning null//Getfloorentry is similar to Getceilingentry, which is no longer spoken here. Final entry<k,v> getfloorentry (K key) {entry<k,v> p = root;while (P! = null) {int CMP = compare (key, p.key); if (CMP > 0) {if (p.right! = null) p = P.right;elsereturn p;} else if (CMP < 0) {if (p.left! = null) {p = p.left;} else {entry<k,v> parent = p.parent; entry<k,v> ch = p;while (parent! = NULL && ch = = parent.left) {ch = parent;parent = parent.parent;} return parent;}} Elsereturn p;} return null;} /*--------------------------------------------------*/public map.entry<k,v> lowerentry (K key) {return Exportentry (Getlowerentry (key));} Public map.entry<k,v> higherentry (K key) {return Exportentry (Gethigherentry (key))}//Gets the smallest node in TreeMap greater than key. If it does not exist, it returns NULL. Please refer to Getceilingentry to understand the gethigherentry. Final entry<k,v> getlowerentry (K key) {entry<k,v> p = root;while (P! = null) {int CMP = compare (key, p.key); if (CMP > 0) {if (p.right! = null) p = P.right;elsereturn p;} else {if (P.LEFT! = null) {p = p.left;} else {entry<k,v> parent = p.parent; entry<k,v> ch = p;while (parent! = NULL && ch = = parent.left) {ch = parent;parent = parent.parent;} return parent;}}} return null;} Gets the largest node of the TreeMap small to key. If it does not exist, it returns NULL. Please refer to Getceilingentry to understand the getlowerentry. Final entry<k,v> gethigherentry (K key) {entry<k,v> p = root;while (P! = null) {int CMP = compare (key, p.key); I F (CMP < 0) {if (p.left! = null) p = P.left;elsereturn p;} else {if (p.right! = null) {p = p.right;} else {entry<k,v& Gt parent = p.parent; entry<k,v> ch = p;while (parent! = NULL && ch = = parent.right) {ch = parent;parent = parent.parent;} return parent;}}} return null;} /*---------------------------------------------------*/2.3 How to construct member properties
After analyzing the entry entity-related source code, let's look at the member properties in TreeMap.
/********** Member properties ****************************/private final comparator<? Super K> Comparator; Comparator private transient entry<k,v> root = null; Entity object private transient int size = 0; The number of red-black tree nodes, that is, entry number private transient int modcount = 0; Number of modifications/*********************** constructor method **************************/public TreeMap () {//default constructor method comparator = null;} Public TreeMap (COMPARATOR<? Super K> Comparator) {//With comparator construction method this.comparator = Comparator;} Public TreeMap (map<? extends K,? extends v> m) {//With map construction method, map will be TreeMap subclass comparator = Null;putall (m);} With SortedMap construction method, SortedMap will be TreeMap subclass public TreeMap (sortedmap<k,? extends v> m) {comparator = M.comparator ( ); try {buildfromsorted (m.size (), M.entryset (). iterator (), NULL, NULL);} catch (Java.io.IOException Cannothappen) {} catch (ClassNotFoundException Cannothappen) {}}
As we can see, TreeMap has four constructors, here we analyze the third constructor, internally called the Putall method, and we look at the Putall method:
public void Putall (map<? extends K,? extends v> Map) {int mapsize = map.size ();//Gets the size of the map//If the TreeMap size is 0 and the map size is not 0 , and map is a sorted key-value pair before executing the following program if (size==0 && mapsize!=0 && map instanceof sortedmap) {Comparator c = ((Sor TEDMAP) (map). Comparator (); if (c = = Comparator | | (c! = null && c.equals (comparator))) {++modcount;try {buildfromsorted (mapsize, Map.entryset (). iterator (), NULL, NULL);} catch (Java.io.IOException Cannothappen) {} catch (ClassNotFoundException cannothappen) {}return;}} Otherwise, the Putall () in Putall ()//abstractmap in Abstractmap will call TreeMap's put () method Super.putall (map);}
Inside the Putall method, the judge first, if the TreeMap is empty, and the incoming map conforms to the conditions, then execute the IF statement, and then call the Buildfromsorted method (followed by the analysis in the source code) to put in, otherwise call the parent class Putall method, The Putall method of the parent class calls the TreeMap put method directly.
Because TreeMap source more, here first write here, the back of the source analysis put to the next blog write: Java collection framework 11--treemap and source Analysis (ii).
If there is any mistake, please feel free to comment
___________________________________________________________________________________________________________ __________________________________________
-----willing to share and progress together!
-----More articles please see: http://blog.csdn.net/eson_15
Java Collection Framework 10--treemap and source Analysis (i)