The unit of map is the processing of key-value pairs, the two previously analyzed map,hashmap and linkedhashmap are hash values to find the key pair we want, the advantage is the search speed of O (1).
So what if we were in a scenario where the requirements for finding performance were not so high, but the order was more demanding ?
This time HashMap is no longer applicable, we need a new map that provides an interface in the JDK: SortedMap, I want to analyze one of the specific implementations: TREEMAP.
Hahmap is key unordered, and TreeMap is key in order.
1. Look at the basic members:
Public classTreemap<k,v>extendsAbstractmap<k,v>ImplementsNavigablemap<k,v>, cloneable, java.io.serializable{Private Finalcomparator<?SuperK>Comparator; Private transiententry<k,v> root =NULL; Private transient intSize = 0; Private transient intModcount = 0; PublicTreeMap () {Comparator=NULL; } PublicTreeMap (comparator<?SuperK>comparator) { This. Comparator =Comparator; } //omitted after}
TreeMap inherited the Navigablemap, and Navigablemap inherited from Sortedmap,navigablemap there are several methods, respectively, is different from the comparison requirements:Floorkey is less than equals, Ceilingkey is greater than or equal, Lowerkey is less than, Higherkey is greater than.
Note that when initializing, there is a comparator member , which is used to maintain an ordered comparator, which can be overridden when we want to make a custom data structure for the treemap.
2. Let's take a look at the members of entry:
Static Final class Implements Map.entry<k,v> { K key; V value; Entrynull; Entrynull; Entry<K,V> parent; boolean color = BLACK; // subsequent ellipsis }
Hey? The wood has the familiar hash value, more left,right,parent, this is our tree structure, finally saw color, understood: TreeMap is based on the red black tree realization! and the default node color is black.
As for the red and black trees, must have heard more or less, this is a balanced two-fork search tree , is a variant of 2-3 trees, which has a two-fork search tree efficient Search, with 2-3 trees of efficient balanced insertion capacity.
The red and black trees subtly increase the color of this dimension, the tree of 2-3 tree itself has been reduced to two fork tree , so that the tree adjustment will not be as cumbersome as 2-3 trees.
Some students see here will question me, you this nonsense, and the introduction of the algorithm is not the same!
Yes, clrs does not have this paragraph, this section selected from the "Algorithms", I think provides an interesting understanding of the idea, so if only to see the clrs, suggest to look at this book, mutual verification.
However, in order to respect the author of the JDK, the following is in accordance with the clrs in the explanation, after all, in the JDK source code of the comments are written: from the CLR.
All of us in the red and black tree after inserting and deleting, in order to maintain the tree's orderly action looks complicated, but is to maintain the following several red and black trees basic properties :
(1) The nodes of the tree are only two colors of red and black.
(2) The root node is black
(3) The leaf node is black
(4) The byte point of the red node must be black.
(5) Starting from any node, the number of black nodes is the same in the path to its successor leaf node
The 4th property of the red and black tree guarantees that no successive red nodes exist in any of these paths, and that the 5th nature of the red and black tree guarantees the same number of black nodes on all these paths. Thus the shortest path must be a path containing only black nodes, and the longest path is the path where the red and black nodes cross each other, since all paths must be black, and red nodes cannot be contiguous, so the longest path is twice times the length of the black node path.
Go back to treemap itself and look at its put method:
Publicv put (K key, V value) {Entry<K,V> T =Root; if(T = =NULL) {Compare (key, key);//type (and possibly null) checkRoot=NewEntry<> (key, value,NULL); Size= 1; Modcount++; return NULL; } intCMP; Entry<K,V>parent; //split comparator and comparable pathscomparator<?Superk> CPR =Comparator; if(CPR! =NULL) { Do{Parent=T; CMP=Cpr.compare (key, T.key); if(CMP < 0) T=T.left; Else if(CMP > 0) T=T.right; Else returnT.setvalue (value); } while(t! =NULL); } Else { if(Key = =NULL) Throw NewNullPointerException (); Comparable<?Superk> k = (comparable<?SuperK>) key; Do{Parent=T; CMP=K.compareto (T.key); if(CMP < 0) T=T.left; Else if(CMP > 0) T=T.right; Else returnT.setvalue (value); } while(t! =NULL); } Entry<K,V> e =NewEntry<>(key, value, parent); if(CMP < 0) Parent.left=e; ElseParent.right=e; Fixafterinsertion (e); Size++; Modcount++; return NULL;}View Code
Here is the binary tree comparison to find a suitable location, and then insert, it is important to note that
(1) First detect if the root node is NULL, if NULL, the newly inserted node is the root node.
(2) It is best to customize your own comparator, otherwise you will inherit the original comparison method, which may cause problems
(3) the inserted key value cannot be null, otherwise a null pointer exception is thrown.
(4) After inserting the new node, call the Fixafterinsertion (e) method to fix the red-black tree.
Take a look at the Get method, where the Getentry method is called, which is the lookup of the binary lookup tree:
FinalEntry<k,v>getentry (Object key) {//Offload comparator-based version for sake of performance if(Comparator! =NULL) returnGetentryusingcomparator (key); if(Key = =NULL) Throw NewNullPointerException (); Comparable<?Superk> k = (comparable<?SuperK>) key; Entry<K,V> p =Root; while(P! =NULL) { intCMP =K.compareto (P.key); if(CMP < 0) P=P.left; Else if(CMP > 0) P=P.right; Else returnp; } return NULL;}View Code
There is also a Remove method, where the last Call is the DeleteEntry () method, and the last call to the Fixafterdeletion method in the DeleteEntry () method to fix the order of the trees.
The deletion of red and black trees is complicated by the heinous of people, looking at the clrs slowly:
Public V Remove (Object key) { Entry<K,V> p = getentry (key); if NULL ) returnnull; = P.value; DeleteEntry (p); return OldValue;}
Private voidDeleteEntry (entry<k,v>p) {Modcount++; Size--; //If strictly Internal, copy successor ' s element to P and then make P//Point to successor. if(P.left! =NULL&& P.right! =NULL) {Entry<K,V> s =successor (p); P.key=S.key; P.value=S.value; P=s; } //P has 2 children//Start fixup at replacement node, if it exists.entry<k,v> replacement = (P.left! =NULL?p.left:p.right); if(Replacement! =NULL) { //Link replacement to parentReplacement.parent =p.parent; if(P.parent = =NULL) Root=replacement; Else if(p = =p.parent.left) P.parent.left=replacement; ElseP.parent.right=replacement; //Null out links so they is OK to use by fixafterdeletion.P.left = P.right = P.parent =NULL; //Fix Replacement if(P.color = =BLACK) fixafterdeletion (replacement); } Else if(P.parent = =NULL) {//return If we are the only node.Root =NULL; } Else{//No Children. use the self as Phantom replacement and unlink. if(P.color = =BLACK) fixafterdeletion (p); if(P.parent! =NULL) { if(p = =p.parent.left) P.parent.left=NULL; Else if(p = =p.parent.right) P.parent.right=NULL; P.parent=NULL; } }}View Code
All the tedious operations above are for the basic nature of the red and black trees, and the operation of the repair sequence is the most basic is left and right, the following is the right-hand and select the source code.
/**From CLR*/Private voidRotateleft (entry<k,v>p) {if(P! =NULL) {Entry<K,V> r =P.right; P.right=R.left; if(R.left! =NULL) R.left.parent=p; R.parent=p.parent; if(P.parent = =NULL) Root=R; Else if(P.parent.left = =p) P.parent.left=R; ElseP.parent.right=R; R.left=p; P.parent=R; }}/**From CLR*/Private voidRotateright (entry<k,v>p) {if(P! =NULL) {Entry<K,V> L =P.left; P.left=L.right; if(L.right! =NULL) L.right.parent =p; L.parent=p.parent; if(P.parent = =NULL) Root=l; Else if(P.parent.right = =p) p.parent.right=l; ElseP.parent.left =l; L.right=p; P.parent=l; }}
In fact, all operations are about the operation of red and black trees,
Determines the order of the TreeMap, and the efficiency of the treemap and additions and deletions is O (Log (n)).
Here, TreeMap in fact almost, the most crucial thing is the operation of the red and black tree, I hope this data structure of knowledge can grasp the more solid bar, read more books, multi-programming, tamping the foundation, and gentlemen mutual encouragement.
TreeMap of the Java collection