FileDocCategorySizeDatePackage
TreeMap.javaAPI DocJava SE 5 API60603Fri Aug 26 14:57:24 BST 2005java.util

TreeMap

public class TreeMap extends AbstractMap implements SortedMap, Cloneable, Serializable
Red-Black tree based implementation of the SortedMap interface. This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable), or by the comparator provided at creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms.

Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new TreeMap(...));

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator throws a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

author
Josh Bloch and Doug Lea
version
1.65, 02/19/04
see
Map
see
HashMap
see
Hashtable
see
Comparable
see
Comparator
see
Collection
see
Collections#synchronizedMap(Map)
since
1.2

Fields Summary
private Comparator
comparator
The Comparator used to maintain order in this TreeMap, or null if this TreeMap uses its elements natural ordering.
private transient Entry
root
private transient int
size
The number of entries in the tree
private transient int
modCount
The number of structural modifications to the tree.
private volatile transient Set
entrySet
This field is initialized to contain an instance of the entry set view the first time this view is requested. The view is stateless, so there's no reason to create more than one.
private static final boolean
RED
private static final boolean
BLACK
private static final long
serialVersionUID
Constructors Summary
public TreeMap()
Constructs a new, empty map, sorted according to the keys' natural order. All keys inserted into the map must implement the Comparable interface. Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any elements k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers), the put(Object key, Object value) call will throw a ClassCastException.

see
Comparable

    
public TreeMap(Comparator c)
Constructs a new, empty map, sorted according to the given comparator. All keys inserted into the map must be mutually comparable by the given comparator: comparator.compare(k1, k2) must not throw a ClassCastException for any keys k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint, the put(Object key, Object value) call will throw a ClassCastException.

param
c the comparator that will be used to sort this map. A null value indicates that the keys' natural ordering should be used.

        this.comparator = c;
    
public TreeMap(Map m)
Constructs a new map containing the same mappings as the given map, sorted according to the keys' natural order. All keys inserted into the new map must implement the Comparable interface. Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any elements k1 and k2 in the map. This method runs in n*log(n) time.

param
m the map whose mappings are to be placed in this map.
throws
ClassCastException the keys in t are not Comparable, or are not mutually comparable.
throws
NullPointerException if the specified map is null.

        putAll(m);
    
public TreeMap(SortedMap m)
Constructs a new map containing the same mappings as the given SortedMap, sorted according to the same ordering. This method runs in linear time.

param
m the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort this map.
throws
NullPointerException if the specified sorted map is null.

        comparator = m.comparator();
        try {
            buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
        } catch (java.io.IOException cannotHappen) {
        } catch (ClassNotFoundException cannotHappen) {
        }
    
Methods Summary
voidaddAllForTreeSet(java.util.SortedSet set, V defaultVal)
Intended to be called only from TreeSet.addAll

	try {
	    buildFromSorted(set.size(), set.iterator(), null, defaultVal);
	} catch (java.io.IOException cannotHappen) {
	} catch (ClassNotFoundException cannotHappen) {
	}
    
private voidbuildFromSorted(int size, java.util.Iterator it, java.io.ObjectInputStream str, V defaultVal)
Linear time tree building algorithm from sorted data. Can accept keys and/or values from iterator or stream. This leads to too many parameters, but seems better than alternatives. The four formats that this method accepts are: 1) An iterator of Map.Entries. (it != null, defaultVal == null). 2) An iterator of keys. (it != null, defaultVal != null). 3) A stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it == null, defaultVal != null). It is assumed that the comparator of the TreeMap is already set prior to calling this method.

param
size the number of keys (or key-value pairs) to be read from the iterator or stream.
param
it If non-null, new entries are created from entries or keys read from this iterator.
param
str If non-null, new entries are created from keys and possibly values read from this stream in serialized form. Exactly one of it and str should be non-null.
param
defaultVal if non-null, this default value is used for each value in the map. If null, each value is read from iterator or stream, as described above.
throws
IOException propagated from stream reads. This cannot occur if str is null.
throws
ClassNotFoundException propagated from readObject. This cannot occur if str is null.

        this.size = size;
        root =
	    buildFromSorted(0, 0, size-1, computeRedLevel(size),
			    it, str, defaultVal);
    
private final java.util.TreeMap$EntrybuildFromSorted(int level, int lo, int hi, int redLevel, java.util.Iterator it, java.io.ObjectInputStream str, V defaultVal)
Recursive "helper method" that does the real work of the of the previous method. Identically named parameters have identical definitions. Additional parameters are documented below. It is assumed that the comparator and size fields of the TreeMap are already set prior to calling this method. (It ignores both fields.)

param
level the current level of tree. Initial call should be 0.
param
lo the first element index of this subtree. Initial should be 0.
param
hi the last element index of this subtree. Initial should be size-1.
param
redLevel the level at which nodes should be red. Must be equal to computeRedLevel for tree of this size.

        /*
         * Strategy: The root is the middlemost element. To get to it, we
         * have to first recursively construct the entire left subtree,
         * so as to grab all of its elements. We can then proceed with right
         * subtree.
         *
         * The lo and hi arguments are the minimum and maximum
         * indices to pull out of the iterator or stream for current subtree.
         * They are not actually indexed, we just proceed sequentially,
         * ensuring that items are extracted in corresponding order.
         */

        if (hi < lo) return null;

        int mid = (lo + hi) / 2;

        Entry<K,V> left  = null;
        if (lo < mid)
            left = buildFromSorted(level+1, lo, mid - 1, redLevel,
				   it, str, defaultVal);

        // extract key and/or value from iterator or stream
        K key;
        V value;
        if (it != null) {
            if (defaultVal==null) {
                Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
                key = entry.getKey();
                value = entry.getValue();
            } else {
                key = (K)it.next();
                value = defaultVal;
            }
        } else { // use stream
            key = (K) str.readObject();
            value = (defaultVal != null ? defaultVal : (V) str.readObject());
        }

        Entry<K,V> middle =  new Entry<K,V>(key, value, null);

        // color nodes in non-full bottommost level red
        if (level == redLevel)
            middle.color = RED;

        if (left != null) {
            middle.left = left;
            left.parent = middle;
        }

        if (mid < hi) {
            Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
					       it, str, defaultVal);
            middle.right = right;
            right.parent = middle;
        }

        return middle;
    
public voidclear()
Removes all mappings from this TreeMap.

        modCount++;
        size = 0;
        root = null;
    
public java.lang.Objectclone()
Returns a shallow copy of this TreeMap instance. (The keys and values themselves are not cloned.)

return
a shallow copy of this Map.

        TreeMap<K,V> clone = null;
        try {
            clone = (TreeMap<K,V>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }

        // Put clone into "virgin" state (except for comparator)
        clone.root = null;
        clone.size = 0;
        clone.modCount = 0;
        clone.entrySet = null;

        // Initialize clone with our mappings
        try {
            clone.buildFromSorted(size, entrySet().iterator(), null, null);
        } catch (java.io.IOException cannotHappen) {
        } catch (ClassNotFoundException cannotHappen) {
        }

        return clone;
    
private static booleancolorOf(java.util.TreeMap$Entry p)
Balancing operations. Implementations of rebalancings during insertion and deletion are slightly different than the CLR version. Rather than using dummy nilnodes, we use a set of accessors that deal properly with null. They are used to avoid messiness surrounding nullness checks in the main algorithms.

        return (p == null ? BLACK : p.color);
    
public java.util.Comparatorcomparator()
Returns the comparator used to order this map, or null if this map uses its keys' natural order.

return
the comparator associated with this sorted map, or null if it uses its keys' natural sort method.

        return comparator;
    
private intcompare(K k1, K k2)
Compares two keys using the correct comparison method for this TreeMap.

        return (comparator==null ? ((Comparable</*-*/K>)k1).compareTo(k2)
                                 : comparator.compare((K)k1, (K)k2));
    
private static intcomputeRedLevel(int sz)
Find the level down to which to assign all nodes BLACK. This is the last `full' level of the complete binary tree produced by buildTree. The remaining nodes are colored RED. (This makes a `nice' set of color assignments wrt future insertions.) This level number is computed by finding the number of splits needed to reach the zeroeth node. (The answer is ~lg(N), but in any case must be computed by same quick O(lg(N)) loop.)

        int level = 0;
        for (int m = sz - 1; m >= 0; m = m / 2 - 1)
            level++;
        return level;
    
public booleancontainsKey(java.lang.Object key)
Returns true if this map contains a mapping for the specified key.

param
key key whose presence in this map is to be tested.
return
true if this map contains a mapping for the specified key.
throws
ClassCastException if the key cannot be compared with the keys currently in the map.
throws
NullPointerException key is null and this map uses natural ordering, or its comparator does not tolerate null keys.

        return getEntry(key) != null;
    
public booleancontainsValue(java.lang.Object value)
Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the Map size for most implementations of Map.

param
value value whose presence in this Map is to be tested.
return
true if a mapping to value exists; false otherwise.
since
1.2

        return (root==null ? false :
                (value==null ? valueSearchNull(root)
                             : valueSearchNonNull(root, value)));
    
private voiddecrementSize()

 modCount++; size--; 
private voiddeleteEntry(java.util.TreeMap$Entry p)
Delete node p, and then rebalance the tree.

        decrementSize();

        // 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 parent
            replacement.parent = p.parent;
            if (p.parent == null)
                root = replacement;
            else if (p == p.parent.left)
                p.parent.left  = replacement;
            else
                p.parent.right = replacement;

            // Null out links so they are 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 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;
            }
        }
    
public java.util.SetentrySet()
Returns a set view of the mappings contained in this map. The set's iterator returns the mappings in ascending key order. Each element in the returned set is a Map.Entry. The set is backed by this map, so changes to this map are reflected in the set, and vice-versa. The set supports element removal, which removes the corresponding mapping from the TreeMap, through the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

return
a set view of the mappings contained in this map.
see
Map.Entry

        if (entrySet == null) {
            entrySet = new AbstractSet<Map.Entry<K,V>>() {
		public Iterator<Map.Entry<K,V>> iterator() {
                    return new EntryIterator();
                }

                public boolean contains(Object o) {
                    if (!(o instanceof Map.Entry))
                        return false;
                    Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
		    V value = entry.getValue();
                    Entry<K,V> p = getEntry(entry.getKey());
                    return p != null && valEquals(p.getValue(), value);
                }

                public boolean remove(Object o) {
                    if (!(o instanceof Map.Entry))
                        return false;
                    Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
		    V value = entry.getValue();
                    Entry<K,V> p = getEntry(entry.getKey());
                    if (p != null && valEquals(p.getValue(), value)) {
                        deleteEntry(p);
                        return true;
                    }
                    return false;
                }

                public int size() {
                    return TreeMap.this.size();
                }

                public void clear() {
                    TreeMap.this.clear();
                }
            };
        }
        return entrySet;
    
private java.util.TreeMap$EntryfirstEntry()
Returns the first Entry in the TreeMap (according to the TreeMap's key-sort function). Returns null if the TreeMap is empty.

        Entry<K,V> p = root;
        if (p != null)
            while (p.left != null)
                p = p.left;
        return p;
    
public KfirstKey()
Returns the first (lowest) key currently in this sorted map.

return
the first (lowest) key currently in this sorted map.
throws
NoSuchElementException Map is empty.

        return key(firstEntry());
    
private voidfixAfterDeletion(java.util.TreeMap$Entry x)
From CLR

        while (x != root && colorOf(x) == BLACK) {
            if (x == leftOf(parentOf(x))) {
                Entry<K,V> sib = rightOf(parentOf(x));

                if (colorOf(sib) == RED) {
                    setColor(sib, BLACK);
                    setColor(parentOf(x), RED);
                    rotateLeft(parentOf(x));
                    sib = rightOf(parentOf(x));
                }

                if (colorOf(leftOf(sib))  == BLACK &&
                    colorOf(rightOf(sib)) == BLACK) {
                    setColor(sib,  RED);
                    x = parentOf(x);
                } else {
                    if (colorOf(rightOf(sib)) == BLACK) {
                        setColor(leftOf(sib), BLACK);
                        setColor(sib, RED);
                        rotateRight(sib);
                        sib = rightOf(parentOf(x));
                    }
                    setColor(sib, colorOf(parentOf(x)));
                    setColor(parentOf(x), BLACK);
                    setColor(rightOf(sib), BLACK);
                    rotateLeft(parentOf(x));
                    x = root;
                }
            } else { // symmetric
                Entry<K,V> sib = leftOf(parentOf(x));

                if (colorOf(sib) == RED) {
                    setColor(sib, BLACK);
                    setColor(parentOf(x), RED);
                    rotateRight(parentOf(x));
                    sib = leftOf(parentOf(x));
                }

                if (colorOf(rightOf(sib)) == BLACK &&
                    colorOf(leftOf(sib)) == BLACK) {
                    setColor(sib,  RED);
                    x = parentOf(x);
                } else {
                    if (colorOf(leftOf(sib)) == BLACK) {
                        setColor(rightOf(sib), BLACK);
                        setColor(sib, RED);
                        rotateLeft(sib);
                        sib = leftOf(parentOf(x));
                    }
                    setColor(sib, colorOf(parentOf(x)));
                    setColor(parentOf(x), BLACK);
                    setColor(leftOf(sib), BLACK);
                    rotateRight(parentOf(x));
                    x = root;
                }
            }
        }

        setColor(x, BLACK);
    
private voidfixAfterInsertion(java.util.TreeMap$Entry x)
From CLR

        x.color = RED;

        while (x != null && x != root && x.parent.color == RED) {
            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
                Entry<K,V> y = rightOf(parentOf(parentOf(x)));
                if (colorOf(y) == RED) {
                    setColor(parentOf(x), BLACK);
                    setColor(y, BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    x = parentOf(parentOf(x));
                } else {
                    if (x == rightOf(parentOf(x))) {
                        x = parentOf(x);
                        rotateLeft(x);
                    }
                    setColor(parentOf(x), BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    if (parentOf(parentOf(x)) != null)
                        rotateRight(parentOf(parentOf(x)));
                }
            } else {
                Entry<K,V> y = leftOf(parentOf(parentOf(x)));
                if (colorOf(y) == RED) {
                    setColor(parentOf(x), BLACK);
                    setColor(y, BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    x = parentOf(parentOf(x));
                } else {
                    if (x == leftOf(parentOf(x))) {
                        x = parentOf(x);
                        rotateRight(x);
                    }
                    setColor(parentOf(x),  BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    if (parentOf(parentOf(x)) != null)
                        rotateLeft(parentOf(parentOf(x)));
                }
            }
        }
        root.color = BLACK;
    
public Vget(java.lang.Object key)
Returns the value to which this map maps the specified key. Returns null if the map contains no mapping for this key. A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

param
key key whose associated value is to be returned.
return
the value to which this map maps the specified key, or null if the map contains no mapping for the key.
throws
ClassCastException key cannot be compared with the keys currently in the map.
throws
NullPointerException key is null and this map uses natural ordering, or its comparator does not tolerate null keys.
see
#containsKey(Object)

        Entry<K,V> p = getEntry(key);
        return (p==null ? null : p.value);
    
private java.util.TreeMap$EntrygetCeilEntry(K key)
Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the least key greater than the specified key; if no such entry exists (i.e., the greatest key in the Tree is less than the specified key), returns null.

        Entry<K,V> p = root;
        if (p==null)
            return null;

        while (true) {
            int cmp = compare(key, p.key);
            if (cmp == 0) {
                return p;
            } else if (cmp < 0) {
                if (p.left != null)
                    p = p.left;
                else
                    return p;
            } else {
                if (p.right != null) {
                    p = p.right;
                } else {
                    Entry<K,V> parent = p.parent;
                    Entry<K,V> ch = p;
                    while (parent != null && ch == parent.right) {
                        ch = parent;
                        parent = parent.parent;
                    }
                    return parent;
                }
            }
        }
    
private java.util.TreeMap$EntrygetEntry(java.lang.Object key)
Returns this map's entry for the given key, or null if the map does not contain an entry for the key.

return
this map's entry for the given key, or null if the map does not contain an entry for the key.
throws
ClassCastException if the key cannot be compared with the keys currently in the map.
throws
NullPointerException key is null and this map uses natural order, or its comparator does not tolerate * null keys.

        Entry<K,V> p = root;
	K k = (K) key;
        while (p != null) {
            int cmp = compare(k, p.key);
            if (cmp == 0)
                return p;
            else if (cmp < 0)
                p = p.left;
            else
                p = p.right;
        }
        return null;
    
private java.util.TreeMap$EntrygetPrecedingEntry(K key)
Returns the entry for the greatest key less than the specified key; if no such entry exists (i.e., the least key in the Tree is greater than the specified key), returns null.

        Entry<K,V> p = root;
        if (p==null)
            return null;

        while (true) {
            int cmp = compare(key, p.key);
            if (cmp > 0) {
                if (p.right != null)
                    p = p.right;
                else
                    return 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;
                }
            }
        }
    
public java.util.SortedMapheadMap(K toKey)
Returns a view of the portion of this map whose keys are strictly less than toKey. The returned sorted map is backed by this map, so changes in the returned sorted map are reflected in this map, and vice-versa. The returned sorted map supports all optional map operations.

The sorted map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key greater than or equal to toKey.

Note: this method always returns a view that does not contain its (high) endpoint. If you need a view that does contain this endpoint, and the key type allows for calculation of the successor a given key, merely request a headMap bounded by successor(highEndpoint). For example, suppose that suppose that m is a sorted map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are less than or equal to high:

SortedMap head = m.headMap(high+"\0");

param
toKey high endpoint (exclusive) of the headMap.
return
a view of the portion of this map whose keys are strictly less than toKey.
throws
ClassCastException if toKey is not compatible with this map's comparator (or, if the map has no comparator, if toKey does not implement Comparable).
throws
IllegalArgumentException if this map is itself a subMap, headMap, or tailMap, and toKey is not within the specified range of the subMap, headMap, or tailMap.
throws
NullPointerException if toKey is null and this map uses natural order, or its comparator does not tolerate null keys.

        return new SubMap(toKey, true);
    
private voidincrementSize()


          modCount++; size++; 
private static Kkey(java.util.TreeMap$Entry e)
Returns the key corresponding to the specified Entry. Throw NoSuchElementException if the Entry is null.

        if (e==null)
            throw new NoSuchElementException();
        return e.key;
    
public java.util.SetkeySet()
Returns a Set view of the keys contained in this map. The set's iterator will return the keys in ascending order. The map is backed by this TreeMap instance, so changes to this map are reflected in the Set, and vice-versa. The Set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

return
a set view of the keys contained in this TreeMap.


                                                                                                
       
        if (keySet == null) {
            keySet = new AbstractSet<K>() {
                public Iterator<K> iterator() {
                    return new KeyIterator();
                }

                public int size() {
                    return TreeMap.this.size();
                }

                public boolean contains(Object o) {
                    return containsKey(o);
                }

                public boolean remove(Object o) {
                    int oldSize = size;
                    TreeMap.this.remove(o);
                    return size != oldSize;
                }

                public void clear() {
                    TreeMap.this.clear();
                }
            };
        }
        return keySet;
    
private java.util.TreeMap$EntrylastEntry()
Returns the last Entry in the TreeMap (according to the TreeMap's key-sort function). Returns null if the TreeMap is empty.

        Entry<K,V> p = root;
        if (p != null)
            while (p.right != null)
                p = p.right;
        return p;
    
public KlastKey()
Returns the last (highest) key currently in this sorted map.

return
the last (highest) key currently in this sorted map.
throws
NoSuchElementException Map is empty.

        return key(lastEntry());
    
private static java.util.TreeMap$EntryleftOf(java.util.TreeMap$Entry p)

        return (p == null) ? null: p.left;
    
private static java.util.TreeMap$EntryparentOf(java.util.TreeMap$Entry p)

        return (p == null ? null: p.parent);
    
public Vput(K key, V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced.

param
key key with which the specified value is to be associated.
param
value value to be associated with the specified key.
return
previous value associated with specified key, or null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key.
throws
ClassCastException key cannot be compared with the keys currently in the map.
throws
NullPointerException key is null and this map uses natural order, or its comparator does not tolerate null keys.

        Entry<K,V> t = root;

        if (t == null) {
            incrementSize();
            root = new Entry<K,V>(key, value, null);
            return null;
       }

        while (true) {
            int cmp = compare(key, t.key);
            if (cmp == 0) {
                return t.setValue(value);
            } else if (cmp < 0) {
                if (t.left != null) {
                    t = t.left;
                } else {
                    incrementSize();
                    t.left = new Entry<K,V>(key, value, t);
                    fixAfterInsertion(t.left);
                    return null;
                }
            } else { // cmp > 0
                if (t.right != null) {
                    t = t.right;
                } else {
                    incrementSize();
                    t.right = new Entry<K,V>(key, value, t);
                    fixAfterInsertion(t.right);
                    return null;
                }
            }
        }
    
public voidputAll(java.util.Map map)
Copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of the keys currently in the specified map.

param
map mappings to be stored in this map.
throws
ClassCastException class of a key or value in the specified map prevents it from being stored in this map.
throws
NullPointerException if the given map is null or this map does not permit null keys and a key in the specified map is null.

        int mapSize = map.size();
        if (size==0 && mapSize!=0 && map instanceof SortedMap) {
            Comparator c = ((SortedMap)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;
            }
        }
        super.putAll(map);
    
private voidreadObject(java.io.ObjectInputStream s)
Reconstitute the TreeMap instance from a stream (i.e., deserialize it).

        // Read in the Comparator and any hidden stuff
        s.defaultReadObject();

        // Read in size
        int size = s.readInt();

        buildFromSorted(size, null, s, null);
    
voidreadTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
Intended to be called only from TreeSet.readObject

        buildFromSorted(size, null, s, defaultVal);
    
public Vremove(java.lang.Object key)
Removes the mapping for this key from this TreeMap if present.

param
key key for which mapping should be removed
return
previous value associated with specified key, or null if there was no mapping for key. A null return can also indicate that the map previously associated null with the specified key.
throws
ClassCastException key cannot be compared with the keys currently in the map.
throws
NullPointerException key is null and this map uses natural order, or its comparator does not tolerate null keys.

        Entry<K,V> p = getEntry(key);
        if (p == null)
            return null;

        V oldValue = p.value;
        deleteEntry(p);
        return oldValue;
    
private static java.util.TreeMap$EntryrightOf(java.util.TreeMap$Entry p)

        return (p == null) ? null: p.right;
    
private voidrotateLeft(java.util.TreeMap$Entry p)
From CLR

        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;
        else
            p.parent.right = r;
        r.left = p;
        p.parent = r;
    
private voidrotateRight(java.util.TreeMap$Entry p)
From CLR

        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;
        else p.parent.left = l;
        l.right = p;
        p.parent = l;
    
private static voidsetColor(java.util.TreeMap$Entry p, boolean c)

        if (p != null)
	    p.color = c;
    
public intsize()
Returns the number of key-value mappings in this map.

return
the number of key-value mappings in this map.

        return size;
    
public java.util.SortedMapsubMap(K fromKey, K toKey)
Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. (If fromKey and toKey are equal, the returned sorted map is empty.) The returned sorted map is backed by this map, so changes in the returned sorted map are reflected in this map, and vice-versa. The returned sorted map supports all optional map operations.

The sorted map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key less than fromKey or greater than or equal to toKey.

Note: this method always returns a half-open range (which includes its low endpoint but not its high endpoint). If you need a closed range (which includes both endpoints), and the key type allows for calculation of the successor a given key, merely request the subrange from lowEndpoint to successor(highEndpoint). For example, suppose that m is a sorted map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high, inclusive:

 SortedMap sub = m.submap(low, high+"\0");
A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high, exclusive:
 SortedMap sub = m.subMap(low+"\0", high);

param
fromKey low endpoint (inclusive) of the subMap.
param
toKey high endpoint (exclusive) of the subMap.
return
a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
throws
ClassCastException if fromKey and toKey cannot be compared to one another using this map's comparator (or, if the map has no comparator, using natural ordering).
throws
IllegalArgumentException if fromKey is greater than toKey.
throws
NullPointerException if fromKey or toKey is null and this map uses natural order, or its comparator does not tolerate null keys.

        return new SubMap(fromKey, toKey);
    
private java.util.TreeMap$Entrysuccessor(java.util.TreeMap$Entry t)
Returns the successor of the specified Entry, or null if no such.

        if (t == null)
            return null;
        else if (t.right != null) {
            Entry<K,V> p = t.right;
            while (p.left != null)
                p = p.left;
            return p;
        } else {
            Entry<K,V> p = t.parent;
            Entry<K,V> ch = t;
            while (p != null && ch == p.right) {
                ch = p;
                p = p.parent;
            }
            return p;
        }
    
public java.util.SortedMaptailMap(K fromKey)
Returns a view of the portion of this map whose keys are greater than or equal to fromKey. The returned sorted map is backed by this map, so changes in the returned sorted map are reflected in this map, and vice-versa. The returned sorted map supports all optional map operations.

The sorted map returned by this method will throw an IllegalArgumentException if the user attempts to insert a key less than fromKey.

Note: this method always returns a view that contains its (low) endpoint. If you need a view that does not contain this endpoint, and the element type allows for calculation of the successor a given value, merely request a tailMap bounded by successor(lowEndpoint). For example, suppose that m is a sorted map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are strictly greater than low:

SortedMap tail = m.tailMap(low+"\0");

param
fromKey low endpoint (inclusive) of the tailMap.
return
a view of the portion of this map whose keys are greater than or equal to fromKey.
throws
ClassCastException if fromKey is not compatible with this map's comparator (or, if the map has no comparator, if fromKey does not implement Comparable).
throws
IllegalArgumentException if this map is itself a subMap, headMap, or tailMap, and fromKey is not within the specified range of the subMap, headMap, or tailMap.
throws
NullPointerException if fromKey is null and this map uses natural order, or its comparator does not tolerate null keys.

        return new SubMap(fromKey, false);
    
private static booleanvalEquals(java.lang.Object o1, java.lang.Object o2)
Test two values for equality. Differs from o1.equals(o2) only in that it copes with null o1 properly.

        return (o1==null ? o2==null : o1.equals(o2));
    
private booleanvalueSearchNonNull(java.util.TreeMap$Entry n, java.lang.Object value)

        // Check this node for the value
        if (value.equals(n.value))
            return true;

        // Check left and right subtrees for value
        return (n.left  != null && valueSearchNonNull(n.left, value)) ||
               (n.right != null && valueSearchNonNull(n.right, value));
    
private booleanvalueSearchNull(java.util.TreeMap$Entry n)

        if (n.value == null)
            return true;

        // Check left and right subtrees for value
        return (n.left  != null && valueSearchNull(n.left)) ||
               (n.right != null && valueSearchNull(n.right));
    
public java.util.Collectionvalues()
Returns a collection view of the values contained in this map. The collection's iterator will return the values in the order that their corresponding keys appear in the tree. The collection is backed by this TreeMap instance, so changes to this map are reflected in the collection, and vice-versa. The collection supports element removal, which removes the corresponding mapping from the map through the Iterator.remove, Collection.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

return
a collection view of the values contained in this map.

        if (values == null) {
            values = new AbstractCollection<V>() {
                public Iterator<V> iterator() {
                    return new ValueIterator();
                }

                public int size() {
                    return TreeMap.this.size();
                }

                public boolean contains(Object o) {
                    for (Entry<K,V> e = firstEntry(); e != null; e = successor(e))
                        if (valEquals(e.getValue(), o))
                            return true;
                    return false;
                }

                public boolean remove(Object o) {
                    for (Entry<K,V> e = firstEntry(); e != null; e = successor(e)) {
                        if (valEquals(e.getValue(), o)) {
                            deleteEntry(e);
                            return true;
                        }
                    }
                    return false;
                }

                public void clear() {
                    TreeMap.this.clear();
                }
            };
        }
        return values;
    
private voidwriteObject(java.io.ObjectOutputStream s)
Save the state of the TreeMap instance to a stream (i.e., serialize it).

serialData
The size of the TreeMap (the number of key-value mappings) is emitted (int), followed by the key (Object) and value (Object) for each key-value mapping represented by the TreeMap. The key-value mappings are emitted in key-order (as determined by the TreeMap's Comparator, or by the keys' natural ordering if the TreeMap has no Comparator).


                                                                                                                                                     
       
          
        // Write out the Comparator and any hidden stuff
        s.defaultWriteObject();

        // Write out size (number of Mappings)
        s.writeInt(size);

        // Write out keys and values (alternating)
        for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
            Map.Entry<K,V> e = i.next();
            s.writeObject(e.getKey());
            s.writeObject(e.getValue());
        }