Java Collection series of TreeMap source code analysis

Source: Internet
Author: User
Tags comparable

I. Overview

TreeMap is based on red and black trees. Because TreeMap implements the Java.util.sortMap interface, the mappings in the collection are in a certain order, depending on the natural order of their keys or sorted according to the comparator provided when the mapping is created, based on the construction method used. In addition, the key object in the TreeMap is not allowed to be null.

1. What is a red and black tree?

The red-black tree is a special two-fork sort tree, which has the following basic properties:

    • Each node can only be red or black
    • The root node is black
    • Each leaf node is black.
    • If a node is red, its two child nodes are black
    • All paths from any node to each leaf node contain the same number of black nodes

The specific principle analysis and algorithm design of red black tree can be found in Blog: The principle analysis and algorithm design of red black tree .

2. Two kinds of key sorting methods

Natural sort: All keys of the TreeMap must implement the comparable interface, and all keys should be objects of the same class, otherwise the classcastexception exception will be thrown

Specify sort: This sort needs to pass in a comparator object when constructing treemap, which is responsible for sorting the key in TreeMap

3. Inheritance relationship of TreeMap class
public class Treemap<k,v> extends abstractmap<k,v> implements Navigablemap<k,v>, Cloneable, Seriali Zable

Where the Navigablemap interface is an extended sortmap with a navigation method that returns the closest match for a given search target. Its method lowerEntry , floorEntry ceilingEntry and higherEntry returns the object associated with the key that is less than, less than or equal to, greater than or equal to the given key, and Map.Entry returns if no such key exists null . Similarly, methods lowerKey , floorKey ceilingKey and higherKey only the associated keys are returned. All of these methods are designed for finding entries rather than traversing the entries.

Second, TreeMap source analysis 1, storage structure

TreeMap is based on a red-black tree, and the tree node is defined as follows:

Static Final class Entry<k,v> implements map.entry<k,v>    {        //key        K key;        Value        V value;        Left child        entry<k,v>;        Right child        entry<k,v>;        Parent node        entry<k,v>;        Node Color        Boolean color = BLACK;        Constructor        Entry (K key, V value, entry<k,v> parent)        {            this.key = key;            This.value = value;            This.parent = parent;        }        ......}

2. Constructor function

TreeMap has four kinds of constructors, which correspond to different parameters respectively.

   1. Construct a new, empty tree map using the natural order of the keys Public    TreeMap ()     {        comparator = null;    }    2. Construct a new, empty tree map that is sorted according to the given comparer public    TreeMap (comparator<? Super k> Comparator)    {        This.comparator = comparator;    }    /3. Constructs a new tree map with the same mapping as the given map, which is sorted according to the natural order of its keys public    TreeMap (map<? extends K,? extends v> m)     {        comparator = null;        Putall (m);    }    4. Constructs a new tree map with the same mapping and the same sort order as the specified ordered map 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)        {        }    }

3, TreeMap Common methods

  V put (K key,v value): Adds a key-value pair (Key,value) to the TreeMap

Public V put (K key, V value) {entry<k,v> t = root; If the root node is empty, create a new node (Key,value) as a parameter if (t = = null) {Compare (key, key);//type (and possibly null) che            CK root = new entry<> (key, value, NULL);            size = 1;            modcount++;        return null;        } int cmp;        Entry<k,v> parent; Split comparator and comparable paths comparator<? Super k> CPR = comparator;                Specifies the sort algorithm if (CPR! = null) {do {parent = t;                CMP = Cpr.compare (key, T.key);                if (CMP < 0)//indicates that the key of the new node is less than the current and node key, then the current node's left child node as the new current node t = t.left;                else if (CMP > 0)//indicates that the key of the new node is greater than the current and node key, then the right child node of the current node as the new current node t = t.right;  else return T.setvalue (value);        Equality overrides the old value} while (t! = null); }//If CPR is empty, the default sorting algorithm is used to create the TreeMap collection ELSE {if (key = = null) throw new NullPointerException (); @SuppressWarnings ("unchecked") comparable<?            Super k> K = (comparable<? super K>) key;                do {parent = t;                CMP = K.compareto (T.key);                if (CMP < 0) T = t.left;                else if (cmp > 0) t = t.right;            else return T.setvalue (value);        } while (t! = null);        }//Add the new node as a child of the parent entry<k,v> e = new entry<> (key, value, parent);        if (CMP < 0) Parent.left = e;      else Parent.right = e;        After inserting the new node, call Fixafterinsertion to adjust the red-black tree fixafterinsertion (e);        size++;        modcount++;    return null; }

  set<map.entry<k,v>> EntrySet (): Returns the Set view of the mappings contained in this map

Public set<map.entry<k,v>> EntrySet ()     {        EntrySet es = entryset;        return (es! = null)? Es: (entryset = new EntrySet ());    }

  boolean remove (Object o): If there is a mapping of the key in this TreeMap, delete it

public boolean remove (Object o) {                if (!) ( o instanceof map.entry))                    return false;                Map.entry<k,v> Entry = (map.entry<k,v>) o;                K key = Entry.getkey ();                if (!inrange (key))                    return false;                treemap.entry<k,v> node = m.getentry (key);                if (Node!=null && valequals (Node.getvalue (),                                            Entry.getvalue ()))                {                    m.deleteentry (node);                    return true;                }                return false;            }   }       

Third, TREEMAP Application sample code
public class treemapdemo{public static void Main (string[] args) {//Use the natural order of the keys to construct a new, empty tree map treemap<        String,string> tm=new treemap<> ();        Tm.put ("001", "China");        Tm.put ("003", "United States");        Tm.put ("002", "France");        System.out.println ("Call EntrySet to get the set of key-value pairs:");        Set<entry<string, string>> result=tm.entryset (); For (entry<string, string> result2:result) {System.out.println (Result2.getkey () + "---" +result2.getv        Alue ());        } System.out.println ("Call keyset to get the keyset:");        Set<string> Result3=tm.keyset ();        for (String str:result3) {System.out.println (str);        } System.out.println ("Call values to get a value set:");        Collection result4=tm.values ();                    for (Object str:result4) System.out.println (str);        Create a new TreeMap treemap<string,string> tm2=new treemap<> with a comparator (new Comparatordemo ());        Tm2.put ("001", "China"); Tm2.pUT ("003", "United States");        Tm2.put ("002", "France");        Set<entry<string, string>> result5=tm2.entryset (); For (entry<string, string> result2:result5) {System.out.println (Result2.getkey () + "---" +result2.get        Value ()); }    }}

First build the TreeMap in the natural order of the keys, adding elements and traversing:

  

Then create a new comparer class to implement the comparator interface

public class Comparatordemo implements comparator<string>{public    int Compare (string O1, String O2) {        return 1;}    }

In the TM2 with the comparator, add the elements in the same order as TM1, and then traverse the TM2 with the following results:

  

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Collection series of TreeMap source code analysis

Related Article

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.