Java Collection Source Analysis: TreeMap Source Analysis

Source: Internet
Author: User
Tags comparable constructor insert sort

Objective

This article does not intend to extend the previous several styles (add the annotation to all source code), because to understand all the source code of TreeMap, for bloggers, it does take a lot of time and experience, it seems unlikely to have so much time to invest, Therefore, this is intended to be through the reading source to the TreeMap has a macro grasp, and some of the implementation of some methods to do a more in-depth analysis.

Introduction to red and black trees

TreeMap is based on the red-black tree, this is only a simple introduction to the red-black tree, red-black tree is a special two-fork sort tree, about the binary sort tree, see: http://blog.csdn.net/ns_code/article/details/ 19823463, the red-black tree through some restrictions, so that it does not appear in the two-tree sorting tree Extreme one-sided situation, relative to the binary sort tree, which naturally improves the efficiency of the query.

The basic properties of binary sort trees are as follows:

1, each node can only be red or black

2, the root node is black

3. Each leaf node (nil node, empty node) is black.

4, if a node is red, then its two child nodes are black. That is to say, you cannot have adjacent two red nodes on a single path.

5. All paths from either node to each of its leaves contain the same number of black nodes.

It is the limitations of these properties that make the longest path of any node in a red-black tree to its descendants ' node not longer than twice times the shortest path, so it is a nearly balanced two-prong tree.

This column more highlights: http://www.bianceng.cn/Programming/Java/

When it comes to red and black trees, nature inevitably contrasts with AVL trees. In contrast, the AVL tree is a strict balance of the binary tree, and the red-black tree is not strictly a balanced binary tree, just close to the balance, will not let the height of the tree as the BST Extreme case is equal to the number of nodes. In fact, the use of red and black trees, can also be used to achieve the AVL tree, but the application of red-black tree is very wide, and AVL trees are rarely used. The AVL tree needs to be adjusted more often than the red and black trees (the red and black trees are rotated for up to three times) when inserting and deleting operations are performed. Efficiency is relatively low, and the statistical performance of the red-black tree is better than the AVL tree, of course, the AVL tree in the query efficiency may be more than a chip, but in fact, not much higher.

Red-black Tree Insert delete operation is very simple, is a simple two-fork sorting tree Insert delete operation. The red-black tree is considered to be more abnormal where it is naturally inserted after the deletion of the red-black tree adjustment operation (rotation and coloring), mainly is a lot of situation, limited to space and the knowledge of the blogger is preferred, here does not intend to detail the insertion of the deletion after the adjustment of the red-black tree and its implementation, we have a macroscopic understanding can, For more information, see the Introduction to the algorithm or some related data.

TreeMap Source Analysis

Storage structure

TreeMap is sorted based on the sort of key that each entry represents a node of the red and black tree, and the entry data structure is as follows:

Static Final class Entry<k,v> implements map.entry<k,v> {    
     //key    
     K key;    
     Values    
     V value;    
     Left    
     = null child entry<k,v>;    
     entry<k,v> right    
     = null;    
     The parent node    
     entry<k,v> parent;    
     Current node Color    
     boolean color = black;    
      
     Constructor    
     Entry (K key, V value, entry<k,v> parent) {    
         This.key = key;    
         This.value = value;    
         This.parent = parent;  
}

Construction method

Let's look at the construction method of TreeMap. TreeMap has 4 construction methods altogether.

1. Non-parametric construction method

Public TreeMap () {    
    comparator = null;    
}

Using the parameterless construction method without specifying the comparator, the implementation of the sort relies on the Key.compareto () method, so the key must implement the comparable interface and overwrite the CompareTo method.

2. The construction method with comparator

Public TreeMap (COMPARATOR< super k> Comparator) {    
    this.comparator = Comparator;    
}

Using a construction method with a comparator, the sort relies on the comparator, and key does not need to implement the comparable interface.

3, the construction method with map

Public TreeMap (map<? extends K,? extends v> m) {    
    comparator = null;    
    Putall (m);    
}

The constructor also does not specify a comparer, calling the Putall method to add all the elements in the map to the TreeMap. Putall source code is as follows:

//Add all nodes in the map to the treemap public void Putall (map<? extends K,? extends v> map) {//Get the size of the map    
    int mapsize = Map.size (); If the size of the TreeMap is 0 and the size of the map is not 0, and the map is a sorted "Key-value pair" if (size==0 && mapsize!=0 && map instanceof Sor    
        Tedmap) {Comparator c = (sortedmap) map). Comparator ();    
        If the TreeMap and map's comparators are equal,//The elements of the map are copied to the TreeMap and then returned! 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;    
    }//Call Putall () in Abstractmap;    
The Putall () in Abstractmap will also invoke the put () Super.putall (map) to TreeMap. }

Obviously, if the elements in the map are sorted, call the Buildfromsorted method to copy the elements in the map, which is highlighted in the next construction method, and if the elements in the map are not sorted, call the Abstractmap Putall (map) method , the source code of the method is as follows:

public void Putall (map<. Extends K,? extends v> m) {    
    for map.entry<? extends K,? extends V> E:m.entry Set ()) Put    
        (E.getkey (), E.getvalue ());    

It is obvious that the elements in the map are put (inserted) into the treemap, mainly because the elements in the map are stored in a disorderly manner, so they should be inserted into the red and black trees, so that they are stored in order and satisfy the nature of the red and black tree.

4, the construction method with SortedMap

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) {    
    }    
}

The comparer is first specified as the comparer for m, depending on whether the calling constructor passed the specified constructor when the m was generated, and then invoking the Buildfromsorted method to insert the elements in the sortedmap into the treemap, because the element in the SortedMap is ordered, In fact, it is based on the treemap created by SortedMap to add the corresponding elements in SortedMap to TreeMap.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.