TreeMappublic class TreeMap extends AbstractMap implements NavigableMap, Cloneable, SerializableA Red-Black tree based {@link NavigableMap} implementation.
The map is sorted according to the {@linkplain Comparable natural
ordering} of its keys, or by a {@link Comparator} provided at map
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
{@link Collections#synchronizedSortedMap Collections.synchronizedSortedMap}
method. This is best done at creation time, to prevent accidental
unsynchronized access to the map:
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
The iterators returned by the iterator method of the collections
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 method, the iterator will throw a {@link
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.
All Map.Entry pairs returned by methods in this class
and its views represent snapshots of mappings at the time they were
produced. They do not support the Entry.setValue
method. (Note however that it is possible to change mappings in the
associated map using put.)
This class is a member of the
Java Collections Framework. |
Fields Summary |
---|
private final Comparator | comparatorThe comparator used to maintain order in this tree map, or
null if it uses the natural ordering of its keys. | private transient Entry | root | private transient int | sizeThe number of entries in the tree | private transient int | modCountThe number of structural modifications to the tree. | private transient EntrySet | entrySetFields initialized to contain an instance of the entry set view
the first time this view is requested. Views are stateless, so
there's no reason to create more than one. | private transient KeySet | navigableKeySet | private transient NavigableMap | descendingMap | private static final boolean | RED | private static final boolean | BLACK | private static final long | serialVersionUID |
Constructors Summary |
---|
public TreeMap()Constructs a new, empty tree map, using the natural ordering of its
keys. All keys inserted into the map must implement the {@link
Comparable} interface. Furthermore, all such keys must be
mutually comparable: k1.compareTo(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 (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.
comparator = null;
| public TreeMap(Comparator comparator)Constructs a new, empty tree map, ordered 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.
this.comparator = comparator;
| public TreeMap(Map m)Constructs a new tree map containing the same mappings as the given
map, ordered according to the natural ordering of its keys.
All keys inserted into the new map must implement the {@link
Comparable} interface. Furthermore, all such keys must be
mutually comparable: k1.compareTo(k2) must not throw
a ClassCastException for any keys k1 and
k2 in the map. This method runs in n*log(n) time.
comparator = null;
putAll(m);
| public TreeMap(SortedMap m)Constructs a new tree map containing the same mappings and
using the same ordering as the specified sorted map. This
method runs in linear time.
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
|
Methods Summary |
---|
void | addAllForTreeSet(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 void | buildFromSorted(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.
this.size = size;
root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
it, str, defaultVal);
| private final java.util.TreeMap$Entry | buildFromSorted(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
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.)
/*
* 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 java.util.Map$Entry | ceilingEntry(K key)
return exportEntry(getCeilingEntry(key));
| public K | ceilingKey(K key)
return keyOrNull(getCeilingEntry(key));
| public void | clear()Removes all of the mappings from this map.
The map will be empty after this call returns.
modCount++;
size = 0;
root = null;
| public java.lang.Object | clone()Returns a shallow copy of this TreeMap instance. (The keys and
values themselves are not cloned.)
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;
clone.navigableKeySet = null;
clone.descendingMap = 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 boolean | colorOf(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.Comparator | comparator()
return comparator;
| final int | compare(java.lang.Object k1, java.lang.Object k2)Compares two keys using the correct comparison method for this TreeMap.
return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
: comparator.compare((K)k1, (K)k2);
| private static int | computeRedLevel(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 boolean | containsKey(java.lang.Object key)Returns true if this map contains a mapping for the specified
key.
return getEntry(key) != null;
| public boolean | containsValue(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.
for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
if (valEquals(value, e.value))
return true;
return false;
| private void | deleteEntry(java.util.TreeMap$Entry p)Delete node p, and then rebalance the tree.
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 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;
}
}
| java.util.Iterator | descendingKeyIterator()
return new DescendingKeyIterator(getFirstEntry());
| public java.util.NavigableSet | descendingKeySet()
return descendingMap().navigableKeySet();
| public java.util.NavigableMap | descendingMap()
NavigableMap<K, V> km = descendingMap;
return (km != null) ? km :
(descendingMap = new DescendingSubMap(this,
true, null, true,
true, null, true));
| public java.util.Set | entrySet()Returns a {@link Set} view of the mappings contained in this map.
The set's iterator returns the entries in ascending key order.
The set is backed by the map, so changes to the map are
reflected in the set, and vice-versa. If the map is modified
while an iteration over the set is in progress (except through
the iterator's own remove operation, or through the
setValue operation on a map entry returned by the
iterator) the results of the iteration are undefined. 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.
EntrySet es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
| static java.util.Map$Entry | exportEntry(java.util.TreeMap$Entry e)Return SimpleImmutableEntry for entry, or null if null
return e == null? null :
new AbstractMap.SimpleImmutableEntry<K,V>(e);
| public java.util.Map$Entry | firstEntry()
return exportEntry(getFirstEntry());
| public K | firstKey()
return key(getFirstEntry());
| private void | fixAfterDeletion(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 void | fixAfterInsertion(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);
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);
rotateLeft(parentOf(parentOf(x)));
}
}
}
root.color = BLACK;
| public java.util.Map$Entry | floorEntry(K key)
return exportEntry(getFloorEntry(key));
| public K | floorKey(K key)
return keyOrNull(getFloorEntry(key));
| public V | get(java.lang.Object key)Returns the value to which the specified key is mapped,
or {@code null} if this map contains no mapping for the key.
More formally, if this map contains a mapping from a key
{@code k} to a value {@code v} such that {@code key} compares
equal to {@code k} according to the map's ordering, then this
method returns {@code v}; otherwise it returns {@code null}.
(There can be at most one such mapping.)
A return value of {@code 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 {@code null}.
The {@link #containsKey containsKey} operation may be used to
distinguish these two cases.
Entry<K,V> p = getEntry(key);
return (p==null ? null : p.value);
| final java.util.TreeMap$Entry | getCeilingEntry(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;
while (p != null) {
int cmp = compare(key, p.key);
if (cmp < 0) {
if (p.left != null)
p = p.left;
else
return p;
} else if (cmp > 0) {
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;
}
} else
return p;
}
return null;
| final java.util.TreeMap$Entry | getEntry(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.
// Offload comparator-based version for sake of performance
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;
while (p != null) {
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
| final java.util.TreeMap$Entry | getEntryUsingComparator(java.lang.Object key)Version of getEntry using comparator. Split off from getEntry
for performance. (This is not worth doing for most methods,
that are less dependent on comparator performance, but is
worthwhile here.)
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;
else
return p;
}
}
return null;
| final java.util.TreeMap$Entry | getFirstEntry()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;
| final java.util.TreeMap$Entry | getFloorEntry(K key)Gets the entry corresponding to the specified key; if no such entry
exists, returns the entry for the greatest key less than the specified
key; if no such entry exists, returns null.
Entry<K,V> p = root;
while (p != null) {
int cmp = compare(key, p.key);
if (cmp > 0) {
if (p.right != null)
p = p.right;
else
return 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;
}
} else
return p;
}
return null;
| final java.util.TreeMap$Entry | getHigherEntry(K key)Gets the entry for the least key greater than 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
returns null.
Entry<K,V> p = root;
while (p != null) {
int cmp = compare(key, p.key);
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;
}
}
}
return null;
| final java.util.TreeMap$Entry | getLastEntry()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;
| final java.util.TreeMap$Entry | getLowerEntry(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;
while (p != null) {
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;
}
}
}
return null;
| public java.util.NavigableMap | headMap(K toKey, boolean inclusive)
return new AscendingSubMap(this,
true, null, true,
false, toKey, inclusive);
| public java.util.SortedMap | headMap(K toKey)
return headMap(toKey, false);
| public java.util.Map$Entry | higherEntry(K key)
return exportEntry(getHigherEntry(key));
| public K | higherKey(K key)
return keyOrNull(getHigherEntry(key));
| static K | key(java.util.TreeMap$Entry e)Returns the key corresponding to the specified Entry.
if (e==null)
throw new NoSuchElementException();
return e.key;
| java.util.Iterator | keyIterator()
return new KeyIterator(getFirstEntry());
| static K | keyOrNull(java.util.TreeMap$Entry e)Return key for entry, or null if null
return e == null? null : e.key;
| public java.util.Set | keySet()Returns a {@link Set} view of the keys contained in this map.
The set's iterator returns the keys in ascending order.
The set is backed by the map, so changes to the map are
reflected in the set, and vice-versa. If the map is modified
while an iteration over the set is in progress (except through
the iterator's own remove operation), the results of
the iteration are undefined. 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 navigableKeySet();
| public java.util.Map$Entry | lastEntry()
return exportEntry(getLastEntry());
| public K | lastKey()
return key(getLastEntry());
| private static java.util.TreeMap$Entry | leftOf(java.util.TreeMap$Entry p)
return (p == null) ? null: p.left;
| public java.util.Map$Entry | lowerEntry(K key)
return exportEntry(getLowerEntry(key));
| public K | lowerKey(K key)
return keyOrNull(getLowerEntry(key));
| public java.util.NavigableSet | navigableKeySet()
KeySet<K> nks = navigableKeySet;
return (nks != null) ? nks : (navigableKeySet = new KeySet(this));
| private static java.util.TreeMap$Entry | parentOf(java.util.TreeMap$Entry p)
return (p == null ? null: p.parent);
| public java.util.Map$Entry | pollFirstEntry()
Entry<K,V> p = getFirstEntry();
Map.Entry<K,V> result = exportEntry(p);
if (p != null)
deleteEntry(p);
return result;
| public java.util.Map$Entry | pollLastEntry()
Entry<K,V> p = getLastEntry();
Map.Entry<K,V> result = exportEntry(p);
if (p != null)
deleteEntry(p);
return result;
| static java.util.TreeMap$Entry | predecessor(java.util.TreeMap$Entry t)Returns the predecessor of the specified Entry, or null if no such.
if (t == null)
return null;
else if (t.left != null) {
Entry<K,V> p = t.left;
while (p.right != null)
p = p.right;
return p;
} else {
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
while (p != null && ch == p.left) {
ch = p;
p = p.parent;
}
return p;
}
| public V | put(K key, V value)Associates the specified value with the specified key in this map.
If the map previously contained a mapping for the key, the old
value is replaced.
Entry<K,V> t = root;
if (t == null) {
// TBD:
// 5045147: (coll) Adding null to an empty TreeSet should
// throw NullPointerException
//
// compare(key, key); // type check
root = new Entry<K,V>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> 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
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
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);
}
Entry<K,V> e = new Entry<K,V>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
| public void | putAll(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.
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 void | readObject(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);
| void | readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)Intended to be called only from TreeSet.readObject
buildFromSorted(size, null, s, defaultVal);
| public V | remove(java.lang.Object key)Removes the mapping for this key from this TreeMap if present.
Entry<K,V> p = getEntry(key);
if (p == null)
return null;
V oldValue = p.value;
deleteEntry(p);
return oldValue;
| private static java.util.TreeMap$Entry | rightOf(java.util.TreeMap$Entry p)
return (p == null) ? null: p.right;
| private void | rotateLeft(java.util.TreeMap$Entry p)From CLR
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;
else
p.parent.right = r;
r.left = p;
p.parent = r;
}
| private void | rotateRight(java.util.TreeMap$Entry p)From CLR
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;
else p.parent.left = l;
l.right = p;
p.parent = l;
}
| private static void | setColor(java.util.TreeMap$Entry p, boolean c)
if (p != null)
p.color = c;
| public int | size()Returns the number of key-value mappings in this map.
return size;
| public java.util.NavigableMap | subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)
return new AscendingSubMap(this,
false, fromKey, fromInclusive,
false, toKey, toInclusive);
| public java.util.SortedMap | subMap(K fromKey, K toKey)
return subMap(fromKey, true, toKey, false);
| static java.util.TreeMap$Entry | successor(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.NavigableMap | tailMap(K fromKey, boolean inclusive)
return new AscendingSubMap(this,
false, fromKey, inclusive,
true, null, true);
| public java.util.SortedMap | tailMap(K fromKey)
return tailMap(fromKey, true);
| static final boolean | valEquals(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));
| public java.util.Collection | values()Returns a {@link Collection} view of the values contained in this map.
The collection's iterator returns the values in ascending order
of the corresponding keys.
The collection is backed by the map, so changes to the map are
reflected in the collection, and vice-versa. If the map is
modified while an iteration over the collection is in progress
(except through the iterator's own remove operation),
the results of the iteration are undefined. The collection
supports element removal, which removes the corresponding
mapping from the map, via the Iterator.remove,
Collection.remove, removeAll,
retainAll and clear operations. It does not
support the add or addAll operations.
Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values());
| private void | writeObject(java.io.ObjectOutputStream s)Save the state of the TreeMap instance to a stream (i.e.,
serialize it).
// 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());
}
|
|