--- jsr166/src/main/java/util/TreeMap.java 2004/12/31 13:00:33 1.2 +++ jsr166/src/main/java/util/TreeMap.java 2006/04/20 20:34:37 1.29 @@ -1,26 +1,24 @@ /* * %W% %E% * - * Copyright 2004 Sun Microsystems, Inc. All rights reserved. + * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ -package java.util; - +package java.util; /** - * Red-Black tree based implementation of the NavigableMap 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.

+ * A 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 + *

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.

+ * Rivest's Introduction to Algorithms. * - * Note that the ordering maintained by a sorted map (whether or not an + *

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 @@ -30,30 +28,30 @@ package java.util; * 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.

+ * 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(...));
- * 

+ *

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 all of this class's "collection view methods" are + *

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 or add methods, the iterator throws a - * ConcurrentModificationException. Thus, in the face of concurrent + * 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. + * 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 @@ -61,7 +59,7 @@ package java.util; * 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.

+ * 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 @@ -73,6 +71,9 @@ package java.util; * * Java Collections Framework. * + * @param the type of keys maintained by this map + * @param the type of mapped values + * * @author Josh Bloch and Doug Lea * @version %I%, %G% * @see Map @@ -81,7 +82,6 @@ package java.util; * @see Comparable * @see Comparator * @see Collection - * @see Collections#synchronizedMap(Map) * @since 1.2 */ @@ -90,8 +90,8 @@ public class TreeMap implements NavigableMap, Cloneable, java.io.Serializable { /** - * The Comparator used to maintain order in this TreeMap, or - * null if this TreeMap uses its elements natural ordering. + * The comparator used to maintain order in this tree map, or + * null if it uses the natural ordering of its keys. * * @serial */ @@ -113,64 +113,64 @@ public class TreeMap private void decrementSize() { modCount++; size--; } /** - * 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 + * 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. */ public TreeMap() { } /** - * 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. - */ - public TreeMap(Comparator c) { - this.comparator = c; + * 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. + * + * @param comparator the comparator that will be used to order this map. + * If null, the {@linkplain Comparable natural + * ordering} of the keys will be used. + */ + public TreeMap(Comparator comparator) { + this.comparator = comparator; } /** - * 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. + * 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. + * + * @param m the map whose mappings are to be placed in this map + * @throws ClassCastException if the keys in m are not {@link Comparable}, + * or are not mutually comparable + * @throws NullPointerException if the specified map is null */ public TreeMap(Map m) { putAll(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. + * 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. * * @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. + * and whose comparator is to be used to sort this map + * @throws NullPointerException if the specified map is null */ public TreeMap(SortedMap m) { comparator = m.comparator(); @@ -187,7 +187,7 @@ public class TreeMap /** * Returns the number of key-value mappings in this map. * - * @return the number of key-value mappings in this map. + * @return the number of key-value mappings in this map */ public int size() { return size; @@ -197,15 +197,14 @@ public class TreeMap * Returns true if this map contains a mapping for the specified * key. * - * @param key key whose presence in this map is to be tested. - * + * @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. + * specified key + * @throws ClassCastException if the specified key cannot be compared + * with the keys currently in the map + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys */ public boolean containsKey(Object key) { return getEntry(key) != null; @@ -216,18 +215,18 @@ public class TreeMap * 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. + * operation will probably require time linear in the map size for + * most implementations. * - * @param value value whose presence in this Map is to be tested. - * @return true if a mapping to value exists; - * false otherwise. + * @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 */ public boolean containsValue(Object value) { return (root==null ? false : (value==null ? valueSearchNull(root) - : valueSearchNonNull(root, value))); + : valueSearchNonNull(root, value))); } private boolean valueSearchNull(Entry n) { @@ -236,7 +235,7 @@ public class TreeMap // Check left and right subtrees for value return (n.left != null && valueSearchNull(n.left)) || - (n.right != null && valueSearchNull(n.right)); + (n.right != null && valueSearchNull(n.right)); } private boolean valueSearchNonNull(Entry n, Object value) { @@ -246,76 +245,65 @@ public class TreeMap // Check left and right subtrees for value return (n.left != null && valueSearchNonNull(n.left, value)) || - (n.right != null && valueSearchNonNull(n.right, value)); + (n.right != null && valueSearchNonNull(n.right, value)); } /** - * 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. + * Returns the value to which the specified key is mapped, + * or {@code null} if this map contains no mapping for the key. * - * @see #containsKey(Object) + *

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. + * + * @throws ClassCastException if the specified key cannot be compared + * with the keys currently in the map + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys */ public V get(Object key) { Entry p = getEntry(key); return (p==null ? null : p.value); } - /** - * 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. - */ public Comparator comparator() { return comparator; } /** - * 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. + * @throws NoSuchElementException {@inheritDoc} */ public K firstKey() { return key(getFirstEntry()); } /** - * 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. + * @throws NoSuchElementException {@inheritDoc} */ public K lastKey() { return key(getLastEntry()); } /** - * 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. + * 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 if the class of a key or value in + * the specified map prevents it from being stored in this map + * @throws NullPointerException if the specified map is null or + * the specified map contains a null key and this map does not + * permit null keys */ public void putAll(Map map) { int mapSize = map.size(); @@ -340,18 +328,20 @@ public class TreeMap * 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. + * does not contain an entry for the key + * @throws ClassCastException if the specified key cannot be compared + * with the keys currently in the map + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys */ - private Entry getEntry(Object key) { + final Entry getEntry(Object key) { // Offload comparator-based version for sake of performance if (comparator != null) return getEntryUsingComparator(key); - Comparable k = (Comparable) key; + if (key == null) + throw new NullPointerException(); + Comparable k = (Comparable) key; Entry p = root; while (p != null) { int cmp = k.compareTo(p.key); @@ -371,7 +361,7 @@ public class TreeMap * that are less dependent on comparator performance, but is * worthwhile here.) */ - private Entry getEntryUsingComparator(Object key) { + final Entry getEntryUsingComparator(Object key) { K k = (K) key; Comparator cpr = comparator; Entry p = root; @@ -393,7 +383,7 @@ public class TreeMap * key; if no such entry exists (i.e., the greatest key in the Tree is less * than the specified key), returns null. */ - private Entry getCeilingEntry(K key) { + final Entry getCeilingEntry(K key) { Entry p = root; if (p==null) return null; @@ -427,7 +417,7 @@ public class TreeMap * exists, returns the entry for the greatest key less than the specified * key; if no such entry exists, returns null. */ - private Entry getFloorEntry(K key) { + final Entry getFloorEntry(K key) { Entry p = root; if (p==null) return null; @@ -463,7 +453,7 @@ public class TreeMap * key greater than the specified key; if no such entry exists * returns null. */ - private Entry getHigherEntry(K key) { + final Entry getHigherEntry(K key) { Entry p = root; if (p==null) return null; @@ -496,7 +486,7 @@ public class TreeMap * no such entry exists (i.e., the least key in the Tree is greater than * the specified key), returns null. */ - private Entry getLowerEntry(K key) { + final Entry getLowerEntry(K key) { Entry p = root; if (p==null) return null; @@ -525,10 +515,10 @@ public class TreeMap } /** - * Returns the key corresponding to the specified Entry. Throw - * NoSuchElementException if the Entry is null. + * Returns the key corresponding to the specified Entry. + * @throws NoSuchElementException if the Entry is null */ - private static K key(Entry e) { + static K key(Entry e) { if (e==null) throw new NoSuchElementException(); return e.key; @@ -536,30 +526,36 @@ public class TreeMap /** * Associates the specified value with the specified key in this map. - * If the map previously contained a mapping for this key, the old + * If the map previously contained a mapping for the 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. + * @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. + * @return the previous value associated with key, or + * null if there was no mapping for key. + * (A null return can also indicate that the map + * previously associated null with key.) + * @throws ClassCastException if the specified key cannot be compared + * with the keys currently in the map + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys */ public V put(K key, V value) { Entry t = root; if (t == null) { + // TBD + // if (key == null) { + // if (comparator == null) + // throw new NullPointerException(); + // comparator.compare(key, key); + // } incrementSize(); root = new Entry(key, value, null); return null; - } + } while (true) { int cmp = compare(key, t.key); @@ -591,16 +587,15 @@ public class TreeMap * 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. + * @return the previous value associated with key, or + * null if there was no mapping for key. + * (A null return can also indicate that the map + * previously associated null with key.) + * @throws ClassCastException if the specified key cannot be compared + * with the keys currently in the map + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys */ public V remove(Object key) { Entry p = getEntry(key); @@ -613,7 +608,8 @@ public class TreeMap } /** - * Removes all mappings from this TreeMap. + * Removes all of the mappings from this map. + * The map will be empty after this call returns. */ public void clear() { modCount++; @@ -625,7 +621,7 @@ public class TreeMap * Returns a shallow copy of this TreeMap instance. (The keys and * values themselves are not cloned.) * - * @return a shallow copy of this Map. + * @return a shallow copy of this map */ public Object clone() { TreeMap clone = null; @@ -640,8 +636,8 @@ public class TreeMap clone.size = 0; clone.modCount = 0; clone.entrySet = null; - clone.descendingEntrySet = null; - clone.descendingKeySet = null; + clone.navigableKeySet = null; + clone.descendingMap = null; // Initialize clone with our mappings try { @@ -656,135 +652,87 @@ public class TreeMap // NavigableMap API methods /** - * Returns a key-value mapping associated with the least - * key in this map, or null if the map is empty. - * - * @return an Entry with least key, or null - * if the map is empty. + * @since 1.6 */ public Map.Entry firstEntry() { Entry e = getFirstEntry(); - return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); + return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); } /** - * Returns a key-value mapping associated with the greatest - * key in this map, or null if the map is empty. - * The returned entry does not support - * the Entry.setValue method. - * - * @return an Entry with greatest key, or null - * if the map is empty. + * @since 1.6 */ public Map.Entry lastEntry() { Entry e = getLastEntry(); - return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); + return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); } /** - * Removes and returns a key-value mapping associated with - * the least key in this map, or null if the map is empty. - * - * @return the removed first entry of this map, or null - * if the map is empty. + * @since 1.6 */ public Map.Entry pollFirstEntry() { Entry p = getFirstEntry(); - if (p == null) + if (p == null) return null; - Map.Entry result = new AbstractMap.SimpleImmutableEntry(p); + Map.Entry result = new AbstractMap.SimpleImmutableEntry(p); deleteEntry(p); return result; } /** - * Removes and returns a key-value mapping associated with - * the greatest key in this map, or null if the map is empty. - * - * @return the removed last entry of this map, or null - * if the map is empty. + * @since 1.6 */ public Map.Entry pollLastEntry() { Entry p = getLastEntry(); - if (p == null) + if (p == null) return null; - Map.Entry result = new AbstractMap.SimpleImmutableEntry(p); + Map.Entry result = new AbstractMap.SimpleImmutableEntry(p); deleteEntry(p); return result; } /** - * Returns a key-value mapping associated with the least key - * greater than or equal to the given key, or null if - * there is no such entry. - * - * @param key the key. - * @return an Entry associated with ceiling of given key, or - * null if there is no such Entry. - * @throws ClassCastException if 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. + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @since 1.6 */ - public Map.Entry ceilingEntry(K key) { - Entry e = getCeilingEntry(key); - return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); + public Map.Entry lowerEntry(K key) { + Entry e = getLowerEntry(key); + return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); } - /** - * Returns least key greater than or equal to the given key, or - * null if there is no such key. - * - * @param key the key. - * @return the ceiling key, or null - * if there is no such key. - * @throws ClassCastException if 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. + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @since 1.6 */ - public K ceilingKey(K key) { - Entry e = getCeilingEntry(key); + public K lowerKey(K key) { + Entry e = getLowerEntry(key); return (e == null)? null : e.key; } - - /** - * Returns a key-value mapping associated with the greatest key - * less than or equal to the given key, or null if there - * is no such entry. - * - * @param key the key. - * @return an Entry associated with floor of given key, or null - * if there is no such Entry. - * @throws ClassCastException if 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. + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @since 1.6 */ public Map.Entry floorEntry(K key) { Entry e = getFloorEntry(key); - return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); + return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); } /** - * Returns the greatest key - * less than or equal to the given key, or null if there - * is no such key. - * - * @param key the key. - * @return the floor of given key, or null if there is no - * such key. - * @throws ClassCastException if 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. + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @since 1.6 */ public K floorKey(K key) { Entry e = getFloorEntry(key); @@ -792,76 +740,50 @@ public class TreeMap } /** - * Returns a key-value mapping associated with the least key - * strictly greater than the given key, or null if there - * is no such entry. - * - * @param key the key. - * @return an Entry with least key greater than the given key, or - * null if there is no such Entry. - * @throws ClassCastException if 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. + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @since 1.6 */ - public Map.Entry higherEntry(K key) { - Entry e = getHigherEntry(key); - return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); + public Map.Entry ceilingEntry(K key) { + Entry e = getCeilingEntry(key); + return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); } /** - * Returns the least key strictly greater than the given key, or - * null if there is no such key. - * - * @param key the key. - * @return the least key greater than the given key, or - * null if there is no such key. - * @throws ClassCastException if 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. + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @since 1.6 */ - public K higherKey(K key) { - Entry e = getHigherEntry(key); + public K ceilingKey(K key) { + Entry e = getCeilingEntry(key); return (e == null)? null : e.key; } /** - * Returns a key-value mapping associated with the greatest - * key strictly less than the given key, or null if there is no - * such entry. - * - * @param key the key. - * @return an Entry with greatest key less than the given - * key, or null if there is no such Entry. - * @throws ClassCastException if 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. + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @since 1.6 */ - public Map.Entry lowerEntry(K key) { - Entry e = getLowerEntry(key); - return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); + public Map.Entry higherEntry(K key) { + Entry e = getHigherEntry(key); + return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e); } /** - * Returns the greatest key strictly less than the given key, or - * null if there is no such key. - * - * @param key the key. - * @return the greatest key less than the given - * key, or null if there is no such key. - * @throws ClassCastException if 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. + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if the specified key is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @since 1.6 */ - public K lowerKey(K key) { - Entry e = getLowerEntry(key); + public K higherKey(K key) { + Entry e = getHigherEntry(key); return (e == null)? null : e.key; } @@ -872,88 +794,196 @@ public class TreeMap * the first time this view is requested. Views are stateless, so * there's no reason to create more than one. */ - private transient Set> entrySet = null; - private transient Set> descendingEntrySet = null; - private transient Set descendingKeySet = null; - - transient Set keySet = null; // XXX remove when integrated - transient Collection values = null; // XXX remove when integrated - - /** - * Returns a Set view of the keys contained in this map. The set's - * iterator will return the keys in ascending order. The set 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. + private transient EntrySet entrySet = null; + private transient KeySet navigableKeySet = null; + private transient NavigableMap descendingMap = null; + + /** + * 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. */ public Set keySet() { - Set ks = keySet; - return (ks != null) ? ks : (keySet = new KeySet()); + return navigableKeySet(); } - class KeySet extends AbstractSet { - public Iterator iterator() { - return new KeyIterator(getFirstEntry()); - } - - 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(); - } + /** + * @since 1.6 + */ + public NavigableSet navigableKeySet() { + KeySet nks = navigableKeySet; + return (nks != null) ? nks : (navigableKeySet = new KeySet(this)); } /** - * 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. + * @since 1.6 + */ + public NavigableSet descendingKeySet() { + return descendingMap().navigableKeySet(); + } + + /** + * 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. */ public Collection values() { Collection vs = values; return (vs != null) ? vs : (values = new Values()); } + /** + * 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. + */ + public Set> entrySet() { + EntrySet es = entrySet; + return (es != null) ? es : (entrySet = new EntrySet()); + } + + /** + * @since 1.6 + */ + public NavigableMap descendingMap() { + NavigableMap km = descendingMap; + return (km != null) ? km : + (descendingMap = new DescendingSubMap(this, + true, null, 0, + true, null, 0)); + } + + /** + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if fromKey or toKey is + * null and this map uses natural ordering, or its comparator + * does not permit null keys + * @throws IllegalArgumentException {@inheritDoc} + * @since 1.6 + */ + public NavigableMap subMap(K fromKey, boolean fromInclusive, + K toKey, boolean toInclusive) { + return new AscendingSubMap(this, + false, fromKey, excluded(fromInclusive), + false, toKey, excluded(toInclusive)); + } + + /** + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if toKey is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @throws IllegalArgumentException {@inheritDoc} + * @since 1.6 + */ + public NavigableMap headMap(K toKey, boolean inclusive) { + return new AscendingSubMap(this, + true, null, 0, + false, toKey, excluded(inclusive)); + } + + /** + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if fromKey is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @throws IllegalArgumentException {@inheritDoc} + * @since 1.6 + */ + public NavigableMap tailMap(K fromKey, boolean inclusive) { + return new AscendingSubMap(this, + false, fromKey, excluded(inclusive), + true, null, 0); + } + + /** + * Translates a boolean "inclusive" value to the correct int value + * for the loExcluded or hiExcluded field. + */ + static int excluded(boolean inclusive) { + return inclusive ? 0 : 1; + } + + /** + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if fromKey or toKey is + * null and this map uses natural ordering, or its comparator + * does not permit null keys + * @throws IllegalArgumentException {@inheritDoc} + */ + public SortedMap subMap(K fromKey, K toKey) { + return subMap(fromKey, true, toKey, false); + } + + /** + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if toKey is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @throws IllegalArgumentException {@inheritDoc} + */ + public SortedMap headMap(K toKey) { + return headMap(toKey, false); + } + + /** + * @throws ClassCastException {@inheritDoc} + * @throws NullPointerException if fromKey is null + * and this map uses natural ordering, or its comparator + * does not permit null keys + * @throws IllegalArgumentException {@inheritDoc} + */ + public SortedMap tailMap(K fromKey) { + return tailMap(fromKey, true); + } + + // View class support + class Values extends AbstractCollection { public Iterator iterator() { return new ValueIterator(getFirstEntry()); } - + public int size() { return TreeMap.this.size(); } - + public boolean contains(Object o) { for (Entry e = getFirstEntry(); e != null; e = successor(e)) if (valEquals(e.getValue(), o)) return true; return false; } - + public boolean remove(Object o) { for (Entry e = getFirstEntry(); e != null; e = successor(e)) { if (valEquals(e.getValue(), o)) { @@ -963,36 +993,17 @@ public class TreeMap } return false; } - + public void clear() { TreeMap.this.clear(); } } - /** - * 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 - */ - public Set> entrySet() { - Set> es = entrySet; - return (es != null) ? es : (entrySet = new EntrySet()); - } - class EntrySet extends AbstractSet> { public Iterator> iterator() { return new EntryIterator(getFirstEntry()); } - + public boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; @@ -1001,7 +1012,7 @@ public class TreeMap Entry p = getEntry(entry.getKey()); return p != null && valEquals(p.getValue(), value); } - + public boolean remove(Object o) { if (!(o instanceof Map.Entry)) return false; @@ -1014,400 +1025,416 @@ public class TreeMap } return false; } - + public int size() { return TreeMap.this.size(); } - + public void clear() { TreeMap.this.clear(); } } - /** - * Returns a set view of the mappings contained in this map. The - * set's iterator returns the mappings in descrending 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, in - * descending key order - * @see Map.Entry - */ - public Set> descendingEntrySet() { - Set> es = descendingEntrySet; - return (es != null) ? es : (descendingEntrySet = new DescendingEntrySet()); + /* + * Unlike Values and EntrySet, the KeySet class is static, + * delegating to a NavigableMap to allow use by SubMaps, which + * outweighs the ugliness of needing type-tests for the following + * Iterator methods that are defined appropriately in main versus + * submap classes. + */ + + Iterator keyIterator() { + return new KeyIterator(getFirstEntry()); } - class DescendingEntrySet extends EntrySet { - public Iterator> iterator() { - return new DescendingEntryIterator(getLastEntry()); + Iterator descendingKeyIterator() { + return new DescendingKeyIterator(getFirstEntry()); + } + + static final class KeySet extends AbstractSet implements NavigableSet { + private final NavigableMap m; + KeySet(NavigableMap map) { m = map; } + + public Iterator iterator() { + if (m instanceof TreeMap) + return ((TreeMap)m).keyIterator(); + else + return (Iterator)(((TreeMap.NavigableSubMap)m).keyIterator()); + } + + public Iterator descendingIterator() { + if (m instanceof TreeMap) + return ((TreeMap)m).descendingKeyIterator(); + else + return (Iterator)(((TreeMap.NavigableSubMap)m).descendingKeyIterator()); + } + + public int size() { return m.size(); } + public boolean isEmpty() { return m.isEmpty(); } + public boolean contains(Object o) { return m.containsKey(o); } + public void clear() { m.clear(); } + public E lower(E e) { return m.lowerKey(e); } + public E floor(E e) { return m.floorKey(e); } + public E ceiling(E e) { return m.ceilingKey(e); } + public E higher(E e) { return m.higherKey(e); } + public E first() { return m.firstKey(); } + public E last() { return m.lastKey(); } + public Comparator comparator() { return m.comparator(); } + public E pollFirst() { + Map.Entry e = m.pollFirstEntry(); + return e == null? null : e.getKey(); + } + public E pollLast() { + Map.Entry e = m.pollLastEntry(); + return e == null? null : e.getKey(); + } + public boolean remove(Object o) { + int oldSize = size(); + m.remove(o); + return size() != oldSize; + } + public NavigableSet subSet(E fromElement, + boolean fromInclusive, + E toElement, + boolean toInclusive) { + return new TreeSet + (m.subMap(fromElement, fromInclusive, + toElement, toInclusive)); + } + public NavigableSet headSet(E toElement, boolean inclusive) { + return new TreeSet(m.headMap(toElement, inclusive)); + } + public NavigableSet tailSet(E fromElement, boolean inclusive) { + return new TreeSet(m.tailMap(fromElement, inclusive)); + } + public SortedSet subSet(E fromElement, E toElement) { + return subSet(fromElement, true, toElement, false); + } + public SortedSet headSet(E toElement) { + return headSet(toElement, false); + } + public SortedSet tailSet(E fromElement) { + return tailSet(fromElement, true); + } + public NavigableSet descendingSet() { + return new TreeSet(m.descendingMap()); } } /** - * Returns a Set view of the keys contained in this map. The - * set's iterator will return the keys in descending 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. + * Base class for TreeMap Iterators */ - public Set descendingKeySet() { - Set ks = descendingKeySet; - return (ks != null) ? ks : (descendingKeySet = new DescendingKeySet()); - } - - class DescendingKeySet extends KeySet { - public Iterator iterator() { - return new DescendingKeyIterator(getLastEntry()); + abstract class PrivateEntryIterator implements Iterator { + int expectedModCount = TreeMap.this.modCount; + Entry lastReturned = null; + Entry next; + + PrivateEntryIterator(Entry first) { + next = first; + } + + public final boolean hasNext() { + return next != null; + } + + final Entry nextEntry() { + if (next == null) + throw new NoSuchElementException(); + if (modCount != expectedModCount) + throw new ConcurrentModificationException(); + lastReturned = next; + next = successor(next); + return lastReturned; + } + + final Entry prevEntry() { + if (next == null) + throw new NoSuchElementException(); + if (modCount != expectedModCount) + throw new ConcurrentModificationException(); + lastReturned = next; + next = predecessor(next); + return lastReturned; + } + + public void remove() { + if (lastReturned == null) + throw new IllegalStateException(); + if (modCount != expectedModCount) + throw new ConcurrentModificationException(); + if (lastReturned.left != null && lastReturned.right != null) + next = lastReturned; + deleteEntry(lastReturned); + expectedModCount++; + lastReturned = null; } } - /** - * 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: - *

    NavigableMap 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: - *
    NavigableMap 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. - */ - public NavigableMap subMap(K fromKey, K toKey) { - return new SubMap(fromKey, toKey); + final class EntryIterator extends PrivateEntryIterator> { + EntryIterator(Entry first) { + super(first); + } + public Map.Entry next() { + return nextEntry(); + } } - /** - * 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: - *

-     *     NavigableMap 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. - */ - public NavigableMap headMap(K toKey) { - return new SubMap(toKey, true); - } - - /** - * 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:

-     *     NavigableMap 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. - */ - public NavigableMap tailMap(K fromKey) { - return new SubMap(fromKey, false); - } - - private class SubMap - extends AbstractMap - implements NavigableMap, java.io.Serializable { - private static final long serialVersionUID = -6520786458950516097L; + final class ValueIterator extends PrivateEntryIterator { + ValueIterator(Entry first) { + super(first); + } + public V next() { + return nextEntry().value; + } + } + + final class KeyIterator extends PrivateEntryIterator { + KeyIterator(Entry first) { + super(first); + } + public K next() { + return nextEntry().key; + } + } + + final class DescendingKeyIterator extends PrivateEntryIterator { + DescendingKeyIterator(Entry first) { + super(first); + } + public K next() { + return prevEntry().key; + } + } + + // SubMaps + + static abstract class NavigableSubMap extends AbstractMap + implements NavigableMap, java.io.Serializable { + + /* + * The backing map. + */ + final TreeMap m; + + /** True if low point is from start of backing map */ + boolean fromStart; + + /** + * The low endpoint of this submap in absolute terms, or null + * if fromStart. + */ + K lo; /** - * fromKey is significant only if fromStart is false. Similarly, - * toKey is significant only if toStart is false. + * Zero if the low endpoint is excluded from this submap, one if + * it's included. This field is unused if fromStart. */ - private boolean fromStart = false, toEnd = false; - private K fromKey, toKey; + int loExcluded; - SubMap(K fromKey, K toKey) { - if (compare(fromKey, toKey) > 0) - throw new IllegalArgumentException("fromKey > toKey"); - this.fromKey = fromKey; - this.toKey = toKey; - } + /** True if high point is to End of backing map */ + boolean toEnd; - SubMap(K key, boolean headMap) { - compare(key, key); // Type-check key + /** + * The high endpoint of this submap in absolute terms, or null + * if toEnd. + */ + K hi; - if (headMap) { - fromStart = true; - toKey = key; - } else { - toEnd = true; - fromKey = key; - } - } + /** + * Zero if the high endpoint is excluded from this submap, one if + * it's included. This field is unused if toEnd. + */ + int hiExcluded; - SubMap(boolean fromStart, K fromKey, boolean toEnd, K toKey) { + NavigableSubMap(TreeMap m, + boolean fromStart, K lo, int loExcluded, + boolean toEnd, K hi, int hiExcluded) { + if (!fromStart && !toEnd && m.compare(lo, hi) > 0) + throw new IllegalArgumentException("fromKey > toKey"); + this.m = m; this.fromStart = fromStart; - this.fromKey= fromKey; + this.lo = lo; + this.loExcluded = loExcluded; this.toEnd = toEnd; - this.toKey = toKey; + this.hi = hi; + this.hiExcluded = hiExcluded; } - public boolean isEmpty() { - return entrySet.isEmpty(); + // internal utilities + + final boolean inRange(Object key) { + return (fromStart || m.compare(key, lo) >= loExcluded) + && (toEnd || m.compare(hi, key) >= hiExcluded); } - public boolean containsKey(Object key) { - return inRange((K) key) && TreeMap.this.containsKey(key); + final boolean inClosedRange(Object key) { + return (fromStart || m.compare(key, lo) >= 0) + && (toEnd || m.compare(hi, key) >= 0); } - public V get(Object key) { - if (!inRange((K) key)) - return null; - return TreeMap.this.get(key); + final boolean inRange(Object key, boolean inclusive) { + return inclusive ? inRange(key) : inClosedRange(key); } - public V put(K key, V value) { - if (!inRange(key)) - throw new IllegalArgumentException("key out of range"); - return TreeMap.this.put(key, value); + final boolean tooLow(K key) { + return !fromStart && m.compare(key, lo) < loExcluded; } - public V remove(Object key) { - if (!inRange((K) key)) - return null; - return TreeMap.this.remove(key); + final boolean tooHigh(K key) { + return !toEnd && m.compare(hi, key) < hiExcluded; } - public Comparator comparator() { - return comparator; + + /** Returns the lowest entry in this submap (absolute ordering) */ + final TreeMap.Entry loEntry() { + TreeMap.Entry result = + (fromStart ? m.getFirstEntry() : + (loExcluded == 0 ? m.getCeilingEntry(lo) : + m.getHigherEntry(lo))); + return (result == null || tooHigh(result.key)) ? null : result; } - public K firstKey() { - TreeMap.Entry e = fromStart ? getFirstEntry() : getCeilingEntry(fromKey); - K first = key(e); - if (!toEnd && compare(first, toKey) >= 0) - throw(new NoSuchElementException()); - return first; + /** Returns the highest key in this submap (absolute ordering) */ + final TreeMap.Entry hiEntry() { + TreeMap.Entry result = + (toEnd ? m.getLastEntry() : + (hiExcluded == 0 ? m.getFloorEntry(hi) : + m.getLowerEntry(hi))); + return (result == null || tooLow(result.key)) ? null : result; } - public K lastKey() { - TreeMap.Entry e = toEnd ? getLastEntry() : getLowerEntry(toKey); - K last = key(e); - if (!fromStart && compare(last, fromKey) < 0) - throw(new NoSuchElementException()); - return last; + /** Polls the lowest entry in this submap (absolute ordering) */ + final Map.Entry pollLoEntry() { + TreeMap.Entry e = loEntry(); + if (e == null) + return null; + Map.Entry result = new AbstractMap.SimpleImmutableEntry(e); + m.deleteEntry(e); + return result; } - public Map.Entry firstEntry() { - TreeMap.Entry e = fromStart ? - getFirstEntry() : getCeilingEntry(fromKey); - if (e == null || (!toEnd && compare(e.key, toKey) >= 0)) + /** Polls the highest key in this submap (absolute ordering) */ + final Map.Entry pollHiEntry() { + TreeMap.Entry e = hiEntry(); + if (e == null) return null; - return e; + Map.Entry result = new AbstractMap.SimpleImmutableEntry(e); + m.deleteEntry(e); + return result; } - public Map.Entry lastEntry() { - TreeMap.Entry e = toEnd ? - getLastEntry() : getLowerEntry(toKey); - if (e == null || (!fromStart && compare(e.key, fromKey) < 0)) + /** + * Return the absolute high fence for ascending traversal + */ + final TreeMap.Entry hiFence() { + if (toEnd) return null; - return e; + else if (hiExcluded == 0) + return m.getHigherEntry(hi); + else + return m.getCeilingEntry(hi); } - public Map.Entry pollFirstEntry() { - TreeMap.Entry e = fromStart ? - getFirstEntry() : getCeilingEntry(fromKey); - if (e == null || (!fromStart && compare(e.key, fromKey) < 0)) + /** + * Return the absolute low fence for descending traversal + */ + final TreeMap.Entry loFence() { + if (fromStart) return null; - Map.Entry result = new AbstractMap.SimpleImmutableEntry(e); - deleteEntry(e); - return result; + else if (loExcluded == 0) + return m.getLowerEntry(lo); + else + return m.getFloorEntry(lo); } - public Map.Entry pollLastEntry() { - TreeMap.Entry e = toEnd ? - getLastEntry() : getLowerEntry(toKey); - if (e == null || (!toEnd && compare(e.key, toKey) >= 0)) + + public boolean isEmpty() { + return entrySet().isEmpty(); + } + + public boolean containsKey(Object key) { + return inRange(key) && m.containsKey(key); + } + + public V get(Object key) { + if (!inRange(key)) return null; - Map.Entry result = new AbstractMap.SimpleImmutableEntry(e); - deleteEntry(e); - return result; + return m.get(key); } - private TreeMap.Entry subceiling(K key) { - TreeMap.Entry e = (!fromStart && compare(key, fromKey) < 0)? - getCeilingEntry(fromKey) : getCeilingEntry(key); - if (e == null || (!toEnd && compare(e.key, toKey) >= 0)) + public V put(K key, V value) { + if (!inRange(key)) + throw new IllegalArgumentException("key out of range"); + return m.put(key, value); + } + + public V remove(Object key) { + if (!inRange(key)) return null; - return e; + return m.remove(key); } public Map.Entry ceilingEntry(K key) { - TreeMap.Entry e = subceiling(key); - return e == null? null : new AbstractMap.SimpleImmutableEntry(e); + TreeMap.Entry e = subCeiling(key); + return e == null? null : new AbstractMap.SimpleImmutableEntry(e); } public K ceilingKey(K key) { - TreeMap.Entry e = subceiling(key); + TreeMap.Entry e = subCeiling(key); return e == null? null : e.key; } - - private TreeMap.Entry subhigher(K key) { - TreeMap.Entry e = (!fromStart && compare(key, fromKey) < 0)? - getCeilingEntry(fromKey) : getHigherEntry(key); - if (e == null || (!toEnd && compare(e.key, toKey) >= 0)) - return null; - return e; - } - public Map.Entry higherEntry(K key) { - TreeMap.Entry e = subhigher(key); - return e == null? null : new AbstractMap.SimpleImmutableEntry(e); + TreeMap.Entry e = subHigher(key); + return e == null? null : new AbstractMap.SimpleImmutableEntry(e); } public K higherKey(K key) { - TreeMap.Entry e = subhigher(key); + TreeMap.Entry e = subHigher(key); return e == null? null : e.key; } - private TreeMap.Entry subfloor(K key) { - TreeMap.Entry e = (!toEnd && compare(key, toKey) >= 0)? - getLowerEntry(toKey) : getFloorEntry(key); - if (e == null || (!fromStart && compare(e.key, fromKey) < 0)) - return null; - return e; - } - public Map.Entry floorEntry(K key) { - TreeMap.Entry e = subfloor(key); - return e == null? null : new AbstractMap.SimpleImmutableEntry(e); + TreeMap.Entry e = subFloor(key); + return e == null? null : new AbstractMap.SimpleImmutableEntry(e); } public K floorKey(K key) { - TreeMap.Entry e = subfloor(key); + TreeMap.Entry e = subFloor(key); return e == null? null : e.key; } - private TreeMap.Entry sublower(K key) { - TreeMap.Entry e = (!toEnd && compare(key, toKey) >= 0)? - getLowerEntry(toKey) : getLowerEntry(key); - if (e == null || (!fromStart && compare(e.key, fromKey) < 0)) - return null; - return e; - } - public Map.Entry lowerEntry(K key) { - TreeMap.Entry e = sublower(key); - return e == null? null : new AbstractMap.SimpleImmutableEntry(e); + TreeMap.Entry e = subLower(key); + return e == null? null : new AbstractMap.SimpleImmutableEntry(e); } public K lowerKey(K key) { - TreeMap.Entry e = sublower(key); + TreeMap.Entry e = subLower(key); return e == null? null : e.key; } - private transient Set> entrySet = new EntrySetView(); + abstract Iterator keyIterator(); + abstract Iterator descendingKeyIterator(); - public Set> entrySet() { - return entrySet; + public NavigableSet descendingKeySet() { + return descendingMap().navigableKeySet(); } - private class EntrySetView extends AbstractSet> { + // Views + transient NavigableMap descendingMapView = null; + transient EntrySetView entrySetView = null; + transient KeySet navigableKeySetView = null; + + abstract class EntrySetView extends AbstractSet> { private transient int size = -1, sizeModCount; public int size() { - if (size == -1 || sizeModCount != TreeMap.this.modCount) { - size = 0; sizeModCount = TreeMap.this.modCount; + if (fromStart && toEnd) + return m.size(); + if (size == -1 || sizeModCount != m.modCount) { + sizeModCount = m.modCount; + size = 0; Iterator i = iterator(); while (i.hasNext()) { size++; @@ -1418,7 +1445,8 @@ public class TreeMap } public boolean isEmpty() { - return !iterator().hasNext(); + TreeMap.Entry n = loEntry(); + return n == null || tooHigh(n.key); } public boolean contains(Object o) { @@ -1428,9 +1456,9 @@ public class TreeMap K key = entry.getKey(); if (!inRange(key)) return false; - TreeMap.Entry node = getEntry(key); + TreeMap.Entry node = m.getEntry(key); return node != null && - valEquals(node.getValue(), entry.getValue()); + valEquals(node.getValue(), entry.getValue()); } public boolean remove(Object o) { @@ -1440,261 +1468,433 @@ public class TreeMap K key = entry.getKey(); if (!inRange(key)) return false; - TreeMap.Entry node = getEntry(key); + TreeMap.Entry node = m.getEntry(key); if (node!=null && valEquals(node.getValue(),entry.getValue())){ - deleteEntry(node); + m.deleteEntry(node); return true; } return false; } + } - public Iterator> iterator() { - return new SubMapEntryIterator( - (fromStart ? getFirstEntry() : getCeilingEntry(fromKey)), - (toEnd ? null : getCeilingEntry(toKey))); - } + public NavigableSet navigableKeySet() { + KeySet nksv = navigableKeySetView; + return (nksv != null) ? nksv : + (navigableKeySetView = new TreeMap.KeySet(this)); } - private transient Set> descendingEntrySetView = null; - private transient Set descendingKeySetView = null; + public Set keySet() { + return navigableKeySet(); + } - public Set> descendingEntrySet() { - Set> es = descendingEntrySetView; - return (es != null) ? es : (descendingEntrySetView = new DescendingEntrySetView()); + public SortedMap subMap(K fromKey, K toKey) { + return subMap(fromKey, true, toKey, false); } - public Set descendingKeySet() { - Set ks = descendingKeySetView; - return (ks != null) ? ks : (descendingKeySetView = new DescendingKeySetView()); + public SortedMap headMap(K toKey) { + return headMap(toKey, false); } - private class DescendingEntrySetView extends EntrySetView { - public Iterator> iterator() { - return new DescendingSubMapEntryIterator - ((toEnd ? getLastEntry() : getLowerEntry(toKey)), - (fromStart ? null : getLowerEntry(fromKey))); + public SortedMap tailMap(K fromKey) { + return tailMap(fromKey, true); + } + + + // The following four definitions are correct only for + // ascending submaps. They are overridden in DescendingSubMap. + // They are defined in the base class because the definitions + // in DescendingSubMap rely on those for AscendingSubMap. + + /** + * Returns the entry corresponding to the ceiling of the specified + * key from the perspective of this submap, or null if the submap + * contains no such entry. + */ + TreeMap.Entry subCeiling(K key) { + if (tooLow(key)) + return loEntry(); + TreeMap.Entry e = m.getCeilingEntry(key); + return (e == null || tooHigh(e.key)) ? null : e; + } + + /** + * Returns the entry corresponding to the higher of the specified + * key from the perspective of this submap, or null if the submap + * contains no such entry. + */ + TreeMap.Entry subHigher(K key) { + if (tooLow(key)) + return loEntry(); + TreeMap.Entry e = m.getHigherEntry(key); + return (e == null || tooHigh(e.key)) ? null : e; + } + + /** + * Returns the entry corresponding to the floor of the specified + * key from the perspective of this submap, or null if the submap + * contains no such entry. + */ + TreeMap.Entry subFloor(K key) { + if (tooHigh(key)) + return hiEntry(); + TreeMap.Entry e = m.getFloorEntry(key); + return (e == null || tooLow(e.key)) ? null : e; + } + + /** + * Returns the entry corresponding to the lower of the specified + * key from the perspective of this submap, or null if the submap + * contains no such entry. + */ + TreeMap.Entry subLower(K key) { + if (tooHigh(key)) + return hiEntry(); + TreeMap.Entry e = m.getLowerEntry(key); + return (e == null || tooLow(e.key)) ? null : e; + } + + /** + * Iterators for SubMaps + */ + abstract class SubMapIterator implements Iterator { + int expectedModCount = m.modCount; + TreeMap.Entry lastReturned = null; + TreeMap.Entry next; + final K firstExcludedKey; + + SubMapIterator(TreeMap.Entry first, + TreeMap.Entry firstExcluded) { + next = first; + firstExcludedKey = (firstExcluded == null ? null + : firstExcluded.key); + } + + public final boolean hasNext() { + return next != null && next.key != firstExcludedKey; + } + + final TreeMap.Entry nextEntry() { + if (next == null || next.key == firstExcludedKey) + throw new NoSuchElementException(); + if (m.modCount != expectedModCount) + throw new ConcurrentModificationException(); + lastReturned = next; + next = m.successor(next); + return lastReturned; + } + + final TreeMap.Entry prevEntry() { + if (next == null || next.key == firstExcludedKey) + throw new NoSuchElementException(); + if (m.modCount != expectedModCount) + throw new ConcurrentModificationException(); + lastReturned = next; + next = m.predecessor(next); + return lastReturned; + } + + public void remove() { + if (lastReturned == null) + throw new IllegalStateException(); + if (m.modCount != expectedModCount) + throw new ConcurrentModificationException(); + if (lastReturned.left != null && lastReturned.right != null) + next = lastReturned; + m.deleteEntry(lastReturned); + expectedModCount++; + lastReturned = null; } } - private class DescendingKeySetView extends AbstractSet { - public Iterator iterator() { - return new Iterator() { - private Iterator> i = descendingEntrySet().iterator(); - - public boolean hasNext() { return i.hasNext(); } - public K next() { return i.next().getKey(); } - public void remove() { i.remove(); } - }; + final class SubMapEntryIterator extends SubMapIterator> { + SubMapEntryIterator(TreeMap.Entry first, + TreeMap.Entry firstExcluded) { + super(first, firstExcluded); } - - public int size() { - return SubMap.this.size(); + public Map.Entry next() { + return nextEntry(); } - - public boolean contains(Object k) { - return SubMap.this.containsKey(k); + } + + final class SubMapKeyIterator extends SubMapIterator { + SubMapKeyIterator(TreeMap.Entry first, + TreeMap.Entry firstExcluded) { + super(first, firstExcluded); + } + public K next() { + return nextEntry().key; } } + final class DescendingSubMapEntryIterator extends SubMapIterator> { + DescendingSubMapEntryIterator(TreeMap.Entry last, + TreeMap.Entry lastExcluded) { + super(last, lastExcluded); + } - public NavigableMap subMap(K fromKey, K toKey) { - if (!inRange2(fromKey)) + public Map.Entry next() { + return prevEntry(); + } + } + + final class DescendingSubMapKeyIterator extends SubMapIterator { + DescendingSubMapKeyIterator(TreeMap.Entry last, + TreeMap.Entry lastExcluded) { + super(last, lastExcluded); + } + public K next() { + return prevEntry().key; + } + } + } + + static class AscendingSubMap extends NavigableSubMap { + private static final long serialVersionUID = 912986545866124060L; + + AscendingSubMap(TreeMap m, + boolean fromStart, K lo, int loExcluded, + boolean toEnd, K hi, int hiExcluded) { + super(m, fromStart, lo, loExcluded, toEnd, hi, hiExcluded); + } + + public Comparator comparator() { + return m.comparator(); + } + + public NavigableMap subMap(K fromKey, boolean fromInclusive, + K toKey, boolean toInclusive) { + if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); - if (!inRange2(toKey)) + if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); - return new SubMap(fromKey, toKey); + return new AscendingSubMap(m, + false, fromKey, excluded(fromInclusive), + false, toKey, excluded(toInclusive)); } - public NavigableMap headMap(K toKey) { - if (!inRange2(toKey)) + public NavigableMap headMap(K toKey, boolean inclusive) { + if (!inClosedRange(toKey)) throw new IllegalArgumentException("toKey out of range"); - return new SubMap(fromStart, fromKey, false, toKey); + return new AscendingSubMap(m, + fromStart, lo, loExcluded, + false, toKey, excluded(inclusive)); } - public NavigableMap tailMap(K fromKey) { - if (!inRange2(fromKey)) + public NavigableMap tailMap(K fromKey, boolean inclusive){ + if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); - return new SubMap(false, fromKey, toEnd, toKey); + return new AscendingSubMap(m, + false, fromKey, excluded(inclusive), + toEnd, hi, hiExcluded); } - private boolean inRange(K key) { - return (fromStart || compare(key, fromKey) >= 0) && - (toEnd || compare(key, toKey) < 0); + Iterator keyIterator() { + return new SubMapKeyIterator(loEntry(), hiFence()); } - // This form allows the high endpoint (as well as all legit keys) - private boolean inRange2(K key) { - return (fromStart || compare(key, fromKey) >= 0) && - (toEnd || compare(key, toKey) <= 0); + Iterator descendingKeyIterator() { + return new DescendingSubMapKeyIterator(hiEntry(), loFence()); } - } - /** - * TreeMap Iterator. - */ - abstract class PrivateEntryIterator implements Iterator { - int expectedModCount = TreeMap.this.modCount; - Entry lastReturned = null; - Entry next; + class AscendingEntrySetView extends NavigableSubMap.EntrySetView { + public Iterator> iterator() { + return new SubMapEntryIterator(loEntry(), hiFence()); + } + } - PrivateEntryIterator(Entry first) { - next = first; + public Set> entrySet() { + EntrySetView es = entrySetView; + return (es != null) ? es : new AscendingEntrySetView(); } - public boolean hasNext() { - return next != null; + public K firstKey() { + return key(loEntry()); } - Entry nextEntry() { - if (next == null) - throw new NoSuchElementException(); - if (modCount != expectedModCount) - throw new ConcurrentModificationException(); - lastReturned = next; - next = successor(next); - return lastReturned; + public K lastKey() { + return key(hiEntry()); } - public void remove() { - if (lastReturned == null) - throw new IllegalStateException(); - if (modCount != expectedModCount) - throw new ConcurrentModificationException(); - if (lastReturned.left != null && lastReturned.right != null) - next = lastReturned; - deleteEntry(lastReturned); - expectedModCount++; - lastReturned = null; + public Map.Entry firstEntry() { + return loEntry(); } - } - class EntryIterator extends PrivateEntryIterator> { - EntryIterator(Entry first) { - super(first); + public Map.Entry lastEntry() { + return hiEntry(); } - public Map.Entry next() { - return nextEntry(); + public Map.Entry pollFirstEntry() { + return pollLoEntry(); } - } - class KeyIterator extends PrivateEntryIterator { - KeyIterator(Entry first) { - super(first); + public Map.Entry pollLastEntry() { + return pollHiEntry(); } - public K next() { - return nextEntry().key; + + public NavigableMap descendingMap() { + NavigableMap mv = descendingMapView; + return (mv != null) ? mv : + (descendingMapView = + new DescendingSubMap(m, + fromStart, lo, loExcluded, + toEnd, hi, hiExcluded)); } } - class ValueIterator extends PrivateEntryIterator { - ValueIterator(Entry first) { - super(first); + static class DescendingSubMap extends NavigableSubMap { + private static final long serialVersionUID = 912986545866120460L; + DescendingSubMap(TreeMap m, + boolean fromStart, K lo, int loExcluded, + boolean toEnd, K hi, int hiExcluded) { + super(m, fromStart, lo, loExcluded, toEnd, hi, hiExcluded); } - public V next() { - return nextEntry().value; + + private final Comparator reverseComparator = + Collections.reverseOrder(m.comparator); + + public Comparator comparator() { + return reverseComparator; } - } - class SubMapEntryIterator extends PrivateEntryIterator> { - private final K firstExcludedKey; + public NavigableMap subMap(K fromKey, boolean fromInclusive, + K toKey, boolean toInclusive) { + if (!inRange(fromKey, fromInclusive)) + throw new IllegalArgumentException("fromKey out of range"); + if (!inRange(toKey, toInclusive)) + throw new IllegalArgumentException("toKey out of range"); + return new DescendingSubMap(m, + false, toKey, excluded(toInclusive), + false, fromKey, excluded(fromInclusive)); + } - SubMapEntryIterator(Entry first, Entry firstExcluded) { - super(first); - firstExcludedKey = (firstExcluded == null - ? null - : firstExcluded.key); + public NavigableMap headMap(K toKey, boolean inclusive) { + if (!inRange(toKey, inclusive)) + throw new IllegalArgumentException("toKey out of range"); + return new DescendingSubMap(m, + false, toKey, excluded(inclusive), + toEnd, hi, hiExcluded); } - public boolean hasNext() { - return next != null && next.key != firstExcludedKey; + public NavigableMap tailMap(K fromKey, boolean inclusive){ + if (!inRange(fromKey, inclusive)) + throw new IllegalArgumentException("fromKey out of range"); + return new DescendingSubMap(m, + fromStart, lo, loExcluded, + false, fromKey, excluded(inclusive)); } - public Map.Entry next() { - if (next == null || next.key == firstExcludedKey) - throw new NoSuchElementException(); - return nextEntry(); + Iterator keyIterator() { + return new DescendingSubMapKeyIterator(hiEntry(), loFence()); } - } + Iterator descendingKeyIterator() { + return new SubMapKeyIterator(loEntry(), hiFence()); + } - /** - * Base for Descending Iterators. - */ - abstract class DescendingPrivateEntryIterator extends PrivateEntryIterator { - DescendingPrivateEntryIterator(Entry first) { - super(first); + class DescendingEntrySetView extends NavigableSubMap.EntrySetView { + public Iterator> iterator() { + return new DescendingSubMapEntryIterator(hiEntry(), loFence()); + } } - Entry nextEntry() { - if (next == null) - throw new NoSuchElementException(); - if (modCount != expectedModCount) - throw new ConcurrentModificationException(); - lastReturned = next; - next = predecessor(next); - return lastReturned; + public Set> entrySet() { + EntrySetView es = entrySetView; + return (es != null) ? es : new DescendingEntrySetView(); } - } - class DescendingEntryIterator extends DescendingPrivateEntryIterator> { - DescendingEntryIterator(Entry first) { - super(first); + public K firstKey() { + return key(hiEntry()); } - public Map.Entry next() { - return nextEntry(); + + public K lastKey() { + return key(loEntry()); } - } - class DescendingKeyIterator extends DescendingPrivateEntryIterator { - DescendingKeyIterator(Entry first) { - super(first); + public Map.Entry firstEntry() { + return hiEntry(); } - public K next() { - return nextEntry().key; + + public Map.Entry lastEntry() { + return loEntry(); } - } + public Map.Entry pollFirstEntry() { + return pollHiEntry(); + } - class DescendingSubMapEntryIterator extends DescendingPrivateEntryIterator> { - private final K lastExcludedKey; + public Map.Entry pollLastEntry() { + return pollLoEntry(); + } - DescendingSubMapEntryIterator(Entry last, Entry lastExcluded) { - super(last); - lastExcludedKey = (lastExcluded == null - ? null - : lastExcluded.key); + public NavigableMap descendingMap() { + NavigableMap mv = descendingMapView; + return (mv != null) ? mv : + (descendingMapView = + new AscendingSubMap(m, + fromStart, lo, loExcluded, + toEnd, hi, hiExcluded)); } - public boolean hasNext() { - return next != null && next.key != lastExcludedKey; + @Override TreeMap.Entry subCeiling(K key) { + return super.subFloor(key); } - public Map.Entry next() { - if (next == null || next.key == lastExcludedKey) - throw new NoSuchElementException(); - return nextEntry(); + @Override TreeMap.Entry subHigher(K key) { + return super.subLower(key); } - } + @Override TreeMap.Entry subFloor(K key) { + return super.subCeiling(key); + } + @Override TreeMap.Entry subLower(K key) { + return super.subHigher(key); + } + } /** * Compares two keys using the correct comparison method for this TreeMap. */ - private int compare(K k1, K k2) { - return (comparator==null ? ((Comparable)k1).compareTo(k2) - : comparator.compare((K)k1, (K)k2)); + final int compare(Object k1, Object k2) { + return comparator==null ? ((Comparable)k1).compareTo((K)k2) + : comparator.compare((K)k1, (K)k2); } /** - * Test two values for equality. Differs from o1.equals(o2) only in + * Test two values for equality. Differs from o1.equals(o2) only in * that it copes with null o1 properly. */ - private static boolean valEquals(Object o1, Object o2) { + final static boolean valEquals(Object o1, Object o2) { return (o1==null ? o2==null : o1.equals(o2)); } + /** + * This class exists solely for the sake of serialization + * compatibility with previous releases of TreeMap that did not + * support NavigableMap. It translates an old-version SubMap into + * a new-version AscendingSubMap. This class is never otherwise + * used. + */ + private class SubMap extends AbstractMap + implements SortedMap, java.io.Serializable { + private static final long serialVersionUID = -6520786458950516097L; + private boolean fromStart = false, toEnd = false; + private K fromKey, toKey; + private Object readResolve() { + return new AscendingSubMap(TreeMap.this, + fromStart, fromKey, 0, + toEnd, toKey, 1); + } + public Set> entrySet() { throw new InternalError(); } + public K lastKey() { throw new InternalError(); } + public K firstKey() { throw new InternalError(); } + public SortedMap subMap(K fromKey, K toKey) { throw new InternalError(); } + public SortedMap headMap(K toKey) { throw new InternalError(); } + public SortedMap tailMap(K fromKey) { throw new InternalError(); } + public Comparator comparator() { throw new InternalError(); } + } + + private static final boolean RED = false; private static final boolean BLACK = true; @@ -1703,7 +1903,7 @@ public class TreeMap * user (see Map.Entry). */ - static class Entry implements Map.Entry { + static final class Entry implements Map.Entry { K key; V value; Entry left = null; @@ -1724,7 +1924,7 @@ public class TreeMap /** * Returns the key. * - * @return the key. + * @return the key */ public K getKey() { return key; @@ -1733,7 +1933,7 @@ public class TreeMap /** * Returns the value associated with the key. * - * @return the value associated with the key. + * @return the value associated with the key */ public V getValue() { return value; @@ -1744,7 +1944,7 @@ public class TreeMap * value. * * @return the value associated with the key before this method was - * called. + * called */ public V setValue(V value) { V oldValue = this.value; @@ -1775,7 +1975,7 @@ public class TreeMap * Returns the first Entry in the TreeMap (according to the TreeMap's * key-sort function). Returns null if the TreeMap is empty. */ - private Entry getFirstEntry() { + final Entry getFirstEntry() { Entry p = root; if (p != null) while (p.left != null) @@ -1787,7 +1987,7 @@ public class TreeMap * Returns the last Entry in the TreeMap (according to the TreeMap's * key-sort function). Returns null if the TreeMap is empty. */ - private Entry getLastEntry() { + final Entry getLastEntry() { Entry p = root; if (p != null) while (p.right != null) @@ -1798,7 +1998,7 @@ public class TreeMap /** * Returns the successor of the specified Entry, or null if no such. */ - private Entry successor(Entry t) { + final Entry successor(Entry t) { if (t == null) return null; else if (t.right != null) { @@ -1820,7 +2020,7 @@ public class TreeMap /** * Returns the predecessor of the specified Entry, or null if no such. */ - private Entry predecessor(Entry t) { + final Entry predecessor(Entry t) { if (t == null) return null; else if (t.left != null) { @@ -2091,8 +2291,6 @@ public class TreeMap } } - - /** * Reconstitute the TreeMap instance from a stream (i.e., * deserialize it). @@ -2115,7 +2313,7 @@ public class TreeMap } /** Intended to be called only from TreeSet.addAll **/ - void addAllForTreeSet(SortedSet> set, V defaultVal) { + void addAllForTreeSet(SortedSet set, V defaultVal) { try { buildFromSorted(set.size(), set.iterator(), null, defaultVal); } catch (java.io.IOException cannotHappen) { @@ -2140,7 +2338,7 @@ public class TreeMap * to calling this method. * * @param size the number of keys (or key-value pairs) to be read from - * the iterator or stream. + * 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 @@ -2154,20 +2352,18 @@ public class TreeMap * @throws ClassNotFoundException propagated from readObject. * This cannot occur if str is null. */ - private - void buildFromSorted(int size, Iterator it, - java.io.ObjectInputStream str, - V defaultVal) + private void buildFromSorted(int size, Iterator it, + java.io.ObjectInputStream str, + V defaultVal) throws java.io.IOException, ClassNotFoundException { this.size = size; - root = - buildFromSorted(0, 0, size-1, computeRedLevel(size), - it, str, defaultVal); + root = buildFromSorted(0, 0, size-1, computeRedLevel(size), + it, str, defaultVal); } /** * Recursive "helper method" that does the real work of the - * of the previous method. Identically named parameters have + * 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.) @@ -2175,7 +2371,7 @@ public class TreeMap * @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. + * size-1. * @param redLevel the level at which nodes should be red. * Must be equal to computeRedLevel for tree of this size. */ @@ -2259,5 +2455,4 @@ public class TreeMap level++; return level; } - }