ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
(Generate patch)

Comparing jsr166/src/main/java/util/TreeMap.java (file contents):
Revision 1.1 by dl, Tue Dec 28 12:14:07 2004 UTC vs.
Revision 1.34 by dl, Sun Apr 23 20:59:49 2006 UTC

# Line 1 | Line 1
1   /*
2   * %W% %E%
3   *
4 < * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
4 > * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5   * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6   */
7  
8 < package java.util;  
9 <
8 > package java.util;
9  
10   /**
11 < * Red-Black tree based implementation of the <tt>NavigableMap</tt> interface.
12 < * This class guarantees that the map will be in ascending key order, sorted
13 < * according to the <i>natural order</i> for the key's class (see
14 < * <tt>Comparable</tt>), or by the comparator provided at creation time,
16 < * depending on which constructor is used.<p>
11 > * A Red-Black tree based {@link NavigableMap} implementation.
12 > * The map is sorted according to the {@linkplain Comparable natural
13 > * ordering} of its keys, or by a {@link Comparator} provided at map
14 > * creation time, depending on which constructor is used.
15   *
16 < * This implementation provides guaranteed log(n) time cost for the
16 > * <p>This implementation provides guaranteed log(n) time cost for the
17   * <tt>containsKey</tt>, <tt>get</tt>, <tt>put</tt> and <tt>remove</tt>
18   * operations.  Algorithms are adaptations of those in Cormen, Leiserson, and
19 < * Rivest's <I>Introduction to Algorithms</I>.<p>
19 > * Rivest's <I>Introduction to Algorithms</I>.
20   *
21 < * Note that the ordering maintained by a sorted map (whether or not an
21 > * <p>Note that the ordering maintained by a sorted map (whether or not an
22   * explicit comparator is provided) must be <i>consistent with equals</i> if
23   * this sorted map is to correctly implement the <tt>Map</tt> interface.  (See
24   * <tt>Comparable</tt> or <tt>Comparator</tt> for a precise definition of
# Line 30 | Line 28 | package java.util;
28   * method, so two keys that are deemed equal by this method are, from the
29   * standpoint of the sorted map, equal.  The behavior of a sorted map
30   * <i>is</i> well-defined even if its ordering is inconsistent with equals; it
31 < * just fails to obey the general contract of the <tt>Map</tt> interface.<p>
31 > * just fails to obey the general contract of the <tt>Map</tt> interface.
32   *
33 < * <b>Note that this implementation is not synchronized.</b> If multiple
34 < * threads access a map concurrently, and at least one of the threads modifies
35 < * the map structurally, it <i>must</i> be synchronized externally.  (A
36 < * structural modification is any operation that adds or deletes one or more
37 < * mappings; merely changing the value associated with an existing key is not
38 < * a structural modification.)  This is typically accomplished by
39 < * synchronizing on some object that naturally encapsulates the map.  If no
40 < * such object exists, the map should be "wrapped" using the
41 < * <tt>Collections.synchronizedMap</tt> method.  This is best done at creation
42 < * time, to prevent accidental unsynchronized access to the map:
43 < * <pre>
44 < *     Map m = Collections.synchronizedMap(new TreeMap(...));
45 < * </pre><p>
33 > * <p><strong>Note that this implementation is not synchronized.</strong>
34 > * If multiple threads access a map concurrently, and at least one of the
35 > * threads modifies the map structurally, it <i>must</i> be synchronized
36 > * externally.  (A structural modification is any operation that adds or
37 > * deletes one or more mappings; merely changing the value associated
38 > * with an existing key is not a structural modification.)  This is
39 > * typically accomplished by synchronizing on some object that naturally
40 > * encapsulates the map.
41 > * If no such object exists, the map should be "wrapped" using the
42 > * {@link Collections#synchronizedSortedMap Collections.synchronizedSortedMap}
43 > * method.  This is best done at creation time, to prevent accidental
44 > * unsynchronized access to the map: <pre>
45 > *   SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));</pre>
46   *
47 < * The iterators returned by all of this class's "collection view methods" are
47 > * <p>The iterators returned by the <tt>iterator</tt> method of the collections
48 > * returned by all of this class's "collection view methods" are
49   * <i>fail-fast</i>: if the map is structurally modified at any time after the
50   * iterator is created, in any way except through the iterator's own
51 < * <tt>remove</tt> or <tt>add</tt> methods, the iterator throws a
52 < * <tt>ConcurrentModificationException</tt>.  Thus, in the face of concurrent
51 > * <tt>remove</tt> method, the iterator will throw a {@link
52 > * ConcurrentModificationException}.  Thus, in the face of concurrent
53   * modification, the iterator fails quickly and cleanly, rather than risking
54 < * arbitrary, non-deterministic behavior at an undetermined time in the
56 < * future.
54 > * arbitrary, non-deterministic behavior at an undetermined time in the future.
55   *
56   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
57   * as it is, generally speaking, impossible to make any hard guarantees in the
# Line 61 | Line 59 | package java.util;
59   * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
60   * Therefore, it would be wrong to write a program that depended on this
61   * exception for its correctness:   <i>the fail-fast behavior of iterators
62 < * should be used only to detect bugs.</i><p>
62 > * should be used only to detect bugs.</i>
63   *
64   * <p>All <tt>Map.Entry</tt> pairs returned by methods in this class
65   * and its views represent snapshots of mappings at the time they were
# Line 73 | Line 71 | package java.util;
71   * <a href="{@docRoot}/../guide/collections/index.html">
72   * Java Collections Framework</a>.
73   *
74 + * @param <K> the type of keys maintained by this map
75 + * @param <V> the type of mapped values
76 + *
77   * @author  Josh Bloch and Doug Lea
78   * @version %I%, %G%
79   * @see Map
# Line 81 | Line 82 | package java.util;
82   * @see Comparable
83   * @see Comparator
84   * @see Collection
84 * @see Collections#synchronizedMap(Map)
85   * @since 1.2
86   */
87  
# Line 90 | Line 90 | public class TreeMap<K,V>
90      implements NavigableMap<K,V>, Cloneable, java.io.Serializable
91   {
92      /**
93 <     * The Comparator used to maintain order in this TreeMap, or
94 <     * null if this TreeMap uses its elements natural ordering.
93 >     * The comparator used to maintain order in this tree map, or
94 >     * null if it uses the natural ordering of its keys.
95       *
96       * @serial
97       */
98 <    private Comparator<? super K> comparator = null;
98 >    private final Comparator<? super K> comparator;
99  
100      private transient Entry<K,V> root = null;
101  
# Line 109 | Line 109 | public class TreeMap<K,V>
109       */
110      private transient int modCount = 0;
111  
112    private void incrementSize()   { modCount++; size++; }
113    private void decrementSize()   { modCount++; size--; }
114
112      /**
113 <     * Constructs a new, empty map, sorted according to the keys' natural
114 <     * order.  All keys inserted into the map must implement the
115 <     * <tt>Comparable</tt> interface.  Furthermore, all such keys must be
116 <     * <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a
117 <     * ClassCastException for any elements <tt>k1</tt> and <tt>k2</tt> in the
118 <     * map.  If the user attempts to put a key into the map that violates this
119 <     * constraint (for example, the user attempts to put a string key into a
120 <     * map whose keys are integers), the <tt>put(Object key, Object
121 <     * value)</tt> call will throw a <tt>ClassCastException</tt>.
122 <     *
126 <     * @see Comparable
113 >     * Constructs a new, empty tree map, using the natural ordering of its
114 >     * keys.  All keys inserted into the map must implement the {@link
115 >     * Comparable} interface.  Furthermore, all such keys must be
116 >     * <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw
117 >     * a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and
118 >     * <tt>k2</tt> in the map.  If the user attempts to put a key into the
119 >     * map that violates this constraint (for example, the user attempts to
120 >     * put a string key into a map whose keys are integers), the
121 >     * <tt>put(Object key, Object value)</tt> call will throw a
122 >     * <tt>ClassCastException</tt>.
123       */
124      public TreeMap() {
125 +        comparator = null;
126      }
127  
128      /**
129 <     * Constructs a new, empty map, sorted according to the given comparator.
130 <     * All keys inserted into the map must be <i>mutually comparable</i> by
131 <     * the given comparator: <tt>comparator.compare(k1, k2)</tt> must not
132 <     * throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and
133 <     * <tt>k2</tt> in the map.  If the user attempts to put a key into the
134 <     * map that violates this constraint, the <tt>put(Object key, Object
135 <     * value)</tt> call will throw a <tt>ClassCastException</tt>.
129 >     * Constructs a new, empty tree map, ordered according to the given
130 >     * comparator.  All keys inserted into the map must be <i>mutually
131 >     * comparable</i> by the given comparator: <tt>comparator.compare(k1,
132 >     * k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys
133 >     * <tt>k1</tt> and <tt>k2</tt> in the map.  If the user attempts to put
134 >     * a key into the map that violates this constraint, the <tt>put(Object
135 >     * key, Object value)</tt> call will throw a
136 >     * <tt>ClassCastException</tt>.
137       *
138 <     * @param c the comparator that will be used to sort this map.  A
139 <     *        <tt>null</tt> value indicates that the keys' <i>natural
140 <     *        ordering</i> should be used.
141 <     */
142 <    public TreeMap(Comparator<? super K> c) {
143 <        this.comparator = c;
138 >     * @param comparator the comparator that will be used to order this map.
139 >     *        If <tt>null</tt>, the {@linkplain Comparable natural
140 >     *        ordering} of the keys will be used.
141 >     */
142 >    public TreeMap(Comparator<? super K> comparator) {
143 >        this.comparator = comparator;
144      }
145  
146      /**
147 <     * Constructs a new map containing the same mappings as the given map,
148 <     * sorted according to the keys' <i>natural order</i>.  All keys inserted
149 <     * into the new map must implement the <tt>Comparable</tt> interface.
150 <     * Furthermore, all such keys must be <i>mutually comparable</i>:
151 <     * <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt>
152 <     * for any elements <tt>k1</tt> and <tt>k2</tt> in the map.  This method
153 <     * runs in n*log(n) time.
154 <     *
155 <     * @param  m the map whose mappings are to be placed in this map.
156 <     * @throws ClassCastException the keys in t are not Comparable, or
157 <     *         are not mutually comparable.
158 <     * @throws NullPointerException if the specified map is null.
147 >     * Constructs a new tree map containing the same mappings as the given
148 >     * map, ordered according to the <i>natural ordering</i> of its keys.
149 >     * All keys inserted into the new map must implement the {@link
150 >     * Comparable} interface.  Furthermore, all such keys must be
151 >     * <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw
152 >     * a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and
153 >     * <tt>k2</tt> in the map.  This method runs in n*log(n) time.
154 >     *
155 >     * @param  m the map whose mappings are to be placed in this map
156 >     * @throws ClassCastException if the keys in m are not {@link Comparable},
157 >     *         or are not mutually comparable
158 >     * @throws NullPointerException if the specified map is null
159       */
160      public TreeMap(Map<? extends K, ? extends V> m) {
161 +        comparator = null;
162          putAll(m);
163      }
164  
165      /**
166 <     * Constructs a new map containing the same mappings as the given
167 <     * <tt>SortedMap</tt>, sorted according to the same ordering.  This method
168 <     * runs in linear time.
166 >     * Constructs a new tree map containing the same mappings and
167 >     * using the same ordering as the specified sorted map.  This
168 >     * method runs in linear time.
169       *
170       * @param  m the sorted map whose mappings are to be placed in this map,
171 <     *         and whose comparator is to be used to sort this map.
172 <     * @throws NullPointerException if the specified sorted map is null.
171 >     *         and whose comparator is to be used to sort this map
172 >     * @throws NullPointerException if the specified map is null
173       */
174      public TreeMap(SortedMap<K, ? extends V> m) {
175          comparator = m.comparator();
# Line 187 | Line 186 | public class TreeMap<K,V>
186      /**
187       * Returns the number of key-value mappings in this map.
188       *
189 <     * @return the number of key-value mappings in this map.
189 >     * @return the number of key-value mappings in this map
190       */
191      public int size() {
192          return size;
# Line 197 | Line 196 | public class TreeMap<K,V>
196       * Returns <tt>true</tt> if this map contains a mapping for the specified
197       * key.
198       *
199 <     * @param key key whose presence in this map is to be tested.
201 <     *
199 >     * @param key key whose presence in this map is to be tested
200       * @return <tt>true</tt> if this map contains a mapping for the
201 <     *            specified key.
202 <     * @throws ClassCastException if the key cannot be compared with the keys
203 <     *                  currently in the map.
204 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
205 <     *                  natural ordering, or its comparator does not tolerate
206 <     *            <tt>null</tt> keys.
201 >     *         specified key
202 >     * @throws ClassCastException if the specified key cannot be compared
203 >     *         with the keys currently in the map
204 >     * @throws NullPointerException if the specified key is null
205 >     *         and this map uses natural ordering, or its comparator
206 >     *         does not permit null keys
207       */
208      public boolean containsKey(Object key) {
209          return getEntry(key) != null;
# Line 216 | Line 214 | public class TreeMap<K,V>
214       * specified value.  More formally, returns <tt>true</tt> if and only if
215       * this map contains at least one mapping to a value <tt>v</tt> such
216       * that <tt>(value==null ? v==null : value.equals(v))</tt>.  This
217 <     * operation will probably require time linear in the Map size for most
218 <     * implementations of Map.
217 >     * operation will probably require time linear in the map size for
218 >     * most implementations.
219       *
220 <     * @param value value whose presence in this Map is to be tested.
221 <     * @return  <tt>true</tt> if a mapping to <tt>value</tt> exists;
222 <     *          <tt>false</tt> otherwise.
220 >     * @param value value whose presence in this map is to be tested
221 >     * @return <tt>true</tt> if a mapping to <tt>value</tt> exists;
222 >     *         <tt>false</tt> otherwise
223       * @since 1.2
224       */
225      public boolean containsValue(Object value) {
226 <        return (root==null ? false :
227 <                (value==null ? valueSearchNull(root)
228 <                             : valueSearchNonNull(root, value)));
229 <    }
232 <
233 <    private boolean valueSearchNull(Entry n) {
234 <        if (n.value == null)
235 <            return true;
236 <
237 <        // Check left and right subtrees for value
238 <        return (n.left  != null && valueSearchNull(n.left)) ||
239 <               (n.right != null && valueSearchNull(n.right));
240 <    }
241 <
242 <    private boolean valueSearchNonNull(Entry n, Object value) {
243 <        // Check this node for the value
244 <        if (value.equals(n.value))
245 <            return true;
246 <
247 <        // Check left and right subtrees for value
248 <        return (n.left  != null && valueSearchNonNull(n.left, value)) ||
249 <               (n.right != null && valueSearchNonNull(n.right, value));
226 >        for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
227 >            if (valEquals(value, e.value))
228 >                return true;
229 >        return false;
230      }
231  
232      /**
233 <     * Returns the value to which this map maps the specified key.  Returns
234 <     * <tt>null</tt> if the map contains no mapping for this key.  A return
255 <     * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
256 <     * map contains no mapping for the key; it's also possible that the map
257 <     * explicitly maps the key to <tt>null</tt>.  The <tt>containsKey</tt>
258 <     * operation may be used to distinguish these two cases.
259 <     *
260 <     * @param key key whose associated value is to be returned.
261 <     * @return the value to which this map maps the specified key, or
262 <     *               <tt>null</tt> if the map contains no mapping for the key.
263 <     * @throws    ClassCastException key cannot be compared with the keys
264 <     *                  currently in the map.
265 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
266 <     *                  natural ordering, or its comparator does not tolerate
267 <     *                  <tt>null</tt> keys.
233 >     * Returns the value to which the specified key is mapped,
234 >     * or {@code null} if this map contains no mapping for the key.
235       *
236 <     * @see #containsKey(Object)
236 >     * <p>More formally, if this map contains a mapping from a key
237 >     * {@code k} to a value {@code v} such that {@code key} compares
238 >     * equal to {@code k} according to the map's ordering, then this
239 >     * method returns {@code v}; otherwise it returns {@code null}.
240 >     * (There can be at most one such mapping.)
241 >     *
242 >     * <p>A return value of {@code null} does not <i>necessarily</i>
243 >     * indicate that the map contains no mapping for the key; it's also
244 >     * possible that the map explicitly maps the key to {@code null}.
245 >     * The {@link #containsKey containsKey} operation may be used to
246 >     * distinguish these two cases.
247 >     *
248 >     * @throws ClassCastException if the specified key cannot be compared
249 >     *         with the keys currently in the map
250 >     * @throws NullPointerException if the specified key is null
251 >     *         and this map uses natural ordering, or its comparator
252 >     *         does not permit null keys
253       */
254      public V get(Object key) {
255          Entry<K,V> p = getEntry(key);
256          return (p==null ? null : p.value);
257      }
258  
276    /**
277     * Returns the comparator used to order this map, or <tt>null</tt> if this
278     * map uses its keys' natural order.
279     *
280     * @return the comparator associated with this sorted map, or
281     *                <tt>null</tt> if it uses its keys' natural sort method.
282     */
259      public Comparator<? super K> comparator() {
260          return comparator;
261      }
262  
263      /**
264 <     * Returns the first (lowest) key currently in this sorted map.
289 <     *
290 <     * @return the first (lowest) key currently in this sorted map.
291 <     * @throws    NoSuchElementException Map is empty.
264 >     * @throws NoSuchElementException {@inheritDoc}
265       */
266      public K firstKey() {
267          return key(getFirstEntry());
268      }
269  
270      /**
271 <     * Returns the last (highest) key currently in this sorted map.
299 <     *
300 <     * @return the last (highest) key currently in this sorted map.
301 <     * @throws    NoSuchElementException Map is empty.
271 >     * @throws NoSuchElementException {@inheritDoc}
272       */
273      public K lastKey() {
274          return key(getLastEntry());
275      }
276  
277      /**
278 <     * Copies all of the mappings from the specified map to this map.  These
279 <     * mappings replace any mappings that this map had for any of the keys
280 <     * currently in the specified map.
281 <     *
282 <     * @param     map mappings to be stored in this map.
283 <     * @throws    ClassCastException class of a key or value in the specified
284 <     *                   map prevents it from being stored in this map.
285 <     *
286 <     * @throws NullPointerException if the given map is <tt>null</tt> or
287 <     *         this map does not permit <tt>null</tt> keys and a
318 <     *         key in the specified map is <tt>null</tt>.
278 >     * Copies all of the mappings from the specified map to this map.
279 >     * These mappings replace any mappings that this map had for any
280 >     * of the keys currently in the specified map.
281 >     *
282 >     * @param  map mappings to be stored in this map
283 >     * @throws ClassCastException if the class of a key or value in
284 >     *         the specified map prevents it from being stored in this map
285 >     * @throws NullPointerException if the specified map is null or
286 >     *         the specified map contains a null key and this map does not
287 >     *         permit null keys
288       */
289      public void putAll(Map<? extends K, ? extends V> map) {
290          int mapSize = map.size();
# Line 340 | Line 309 | public class TreeMap<K,V>
309       * does not contain an entry for the key.
310       *
311       * @return this map's entry for the given key, or <tt>null</tt> if the map
312 <     *                does not contain an entry for the key.
313 <     * @throws ClassCastException if the key cannot be compared with the keys
314 <     *                  currently in the map.
315 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
316 <     *                  natural order, or its comparator does not tolerate *
317 <     *                  <tt>null</tt> keys.
312 >     *         does not contain an entry for the key
313 >     * @throws ClassCastException if the specified key cannot be compared
314 >     *         with the keys currently in the map
315 >     * @throws NullPointerException if the specified key is null
316 >     *         and this map uses natural ordering, or its comparator
317 >     *         does not permit null keys
318       */
319 <    private Entry<K,V> getEntry(Object key) {
319 >    final Entry<K,V> getEntry(Object key) {
320          // Offload comparator-based version for sake of performance
321          if (comparator != null)
322              return getEntryUsingComparator(key);
323 <        Comparable<K> k = (Comparable<K>) key;
323 >        if (key == null)
324 >            throw new NullPointerException();
325 >        Comparable<? super K> k = (Comparable<? super K>) key;
326          Entry<K,V> p = root;
327          while (p != null) {
328              int cmp = k.compareTo(p.key);
# Line 371 | Line 342 | public class TreeMap<K,V>
342       * that are less dependent on comparator performance, but is
343       * worthwhile here.)
344       */
345 <    private Entry<K,V> getEntryUsingComparator(Object key) {
345 >    final Entry<K,V> getEntryUsingComparator(Object key) {
346          K k = (K) key;
347          Comparator<? super K> cpr = comparator;
348 <        Entry<K,V> p = root;
349 <        while (p != null) {
350 <            int cmp = cpr.compare(k, p.key);
351 <            if (cmp < 0)
352 <                p = p.left;
353 <            else if (cmp > 0)
354 <                p = p.right;
355 <            else
356 <                return p;
348 >        if (cpr != null) {
349 >            Entry<K,V> p = root;
350 >            while (p != null) {
351 >                int cmp = cpr.compare(k, p.key);
352 >                if (cmp < 0)
353 >                    p = p.left;
354 >                else if (cmp > 0)
355 >                    p = p.right;
356 >                else
357 >                    return p;
358 >            }
359          }
360          return null;
361      }
# Line 393 | Line 366 | public class TreeMap<K,V>
366       * key; if no such entry exists (i.e., the greatest key in the Tree is less
367       * than the specified key), returns <tt>null</tt>.
368       */
369 <    private Entry<K,V> getCeilingEntry(K key) {
369 >    final Entry<K,V> getCeilingEntry(K key) {
370          Entry<K,V> p = root;
371 <        if (p==null)
399 <            return null;
400 <
401 <        while (true) {
371 >        while (p != null) {
372              int cmp = compare(key, p.key);
373              if (cmp < 0) {
374                  if (p.left != null)
# Line 420 | Line 390 | public class TreeMap<K,V>
390              } else
391                  return p;
392          }
393 +        return null;
394      }
395  
396      /**
# Line 427 | Line 398 | public class TreeMap<K,V>
398       * exists, returns the entry for the greatest key less than the specified
399       * key; if no such entry exists, returns <tt>null</tt>.
400       */
401 <    private Entry<K,V> getFloorEntry(K key) {
401 >    final Entry<K,V> getFloorEntry(K key) {
402          Entry<K,V> p = root;
403 <        if (p==null)
433 <            return null;
434 <
435 <        while (true) {
403 >        while (p != null) {
404              int cmp = compare(key, p.key);
405              if (cmp > 0) {
406                  if (p.right != null)
# Line 455 | Line 423 | public class TreeMap<K,V>
423                  return p;
424  
425          }
426 +        return null;
427      }
428  
429      /**
# Line 463 | Line 432 | public class TreeMap<K,V>
432       * key greater than the specified key; if no such entry exists
433       * returns <tt>null</tt>.
434       */
435 <    private Entry<K,V> getHigherEntry(K key) {
435 >    final Entry<K,V> getHigherEntry(K key) {
436          Entry<K,V> p = root;
437 <        if (p==null)
469 <            return null;
470 <
471 <        while (true) {
437 >        while (p != null) {
438              int cmp = compare(key, p.key);
439              if (cmp < 0) {
440                  if (p.left != null)
# Line 489 | Line 455 | public class TreeMap<K,V>
455                  }
456              }
457          }
458 +        return null;
459      }
460  
461      /**
# Line 496 | Line 463 | public class TreeMap<K,V>
463       * no such entry exists (i.e., the least key in the Tree is greater than
464       * the specified key), returns <tt>null</tt>.
465       */
466 <    private Entry<K,V> getLowerEntry(K key) {
466 >    final Entry<K,V> getLowerEntry(K key) {
467          Entry<K,V> p = root;
468 <        if (p==null)
502 <            return null;
503 <
504 <        while (true) {
468 >        while (p != null) {
469              int cmp = compare(key, p.key);
470              if (cmp > 0) {
471                  if (p.right != null)
# Line 522 | Line 486 | public class TreeMap<K,V>
486                  }
487              }
488          }
489 <    }
526 <
527 <    /**
528 <     * Returns the key corresponding to the specified Entry.  Throw
529 <     * NoSuchElementException if the Entry is <tt>null</tt>.
530 <     */
531 <    private static <K> K key(Entry<K,?> e) {
532 <        if (e==null)
533 <            throw new NoSuchElementException();
534 <        return e.key;
489 >        return null;
490      }
491  
492      /**
493       * Associates the specified value with the specified key in this map.
494 <     * If the map previously contained a mapping for this key, the old
494 >     * If the map previously contained a mapping for the key, the old
495       * value is replaced.
496       *
497 <     * @param key key with which the specified value is to be associated.
498 <     * @param value value to be associated with the specified key.
497 >     * @param key key with which the specified value is to be associated
498 >     * @param value value to be associated with the specified key
499       *
500 <     * @return previous value associated with specified key, or <tt>null</tt>
501 <     *         if there was no mapping for key.  A <tt>null</tt> return can
502 <     *         also indicate that the map previously associated <tt>null</tt>
503 <     *         with the specified key.
504 <     * @throws    ClassCastException key cannot be compared with the keys
505 <     *            currently in the map.
506 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
507 <     *         natural order, or its comparator does not tolerate
508 <     *         <tt>null</tt> keys.
500 >     * @return the previous value associated with <tt>key</tt>, or
501 >     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
502 >     *         (A <tt>null</tt> return can also indicate that the map
503 >     *         previously associated <tt>null</tt> with <tt>key</tt>.)
504 >     * @throws ClassCastException if the specified key cannot be compared
505 >     *         with the keys currently in the map
506 >     * @throws NullPointerException if the specified key is null
507 >     *         and this map uses natural ordering, or its comparator
508 >     *         does not permit null keys
509       */
510      public V put(K key, V value) {
511          Entry<K,V> t = root;
557
512          if (t == null) {
513 <            incrementSize();
513 >            compare(key, key); // type check
514              root = new Entry<K,V>(key, value, null);
515 +            size = 1;
516 +            modCount++;
517              return null;
518 <       }
519 <
520 <        while (true) {
521 <            int cmp = compare(key, t.key);
522 <            if (cmp == 0) {
523 <                return t.setValue(value);
524 <            } else if (cmp < 0) {
525 <                if (t.left != null) {
518 >        }
519 >        int cmp;
520 >        Entry<K,V> parent;
521 >        // split comparator and comparable paths
522 >        Comparator<? super K> cpr = comparator;
523 >        if (cpr != null) {
524 >            do {
525 >                parent = t;
526 >                cmp = cpr.compare(key, t.key);
527 >                if (cmp < 0)
528                      t = t.left;
529 <                } else {
572 <                    incrementSize();
573 <                    t.left = new Entry<K,V>(key, value, t);
574 <                    fixAfterInsertion(t.left);
575 <                    return null;
576 <                }
577 <            } else { // cmp > 0
578 <                if (t.right != null) {
529 >                else if (cmp > 0)
530                      t = t.right;
531 <                } else {
532 <                    incrementSize();
533 <                    t.right = new Entry<K,V>(key, value, t);
534 <                    fixAfterInsertion(t.right);
535 <                    return null;
536 <                }
537 <            }
531 >                else
532 >                    return t.setValue(value);
533 >            } while (t != null);
534 >        }
535 >        else {
536 >            if (key == null)
537 >                throw new NullPointerException();
538 >            Comparable<? super K> k = (Comparable<? super K>) key;
539 >            do {
540 >                parent = t;
541 >                cmp = k.compareTo(t.key);
542 >                if (cmp < 0)
543 >                    t = t.left;
544 >                else if (cmp > 0)
545 >                    t = t.right;
546 >                else
547 >                    return t.setValue(value);
548 >            } while (t != null);
549          }
550 +        Entry<K,V> e = new Entry<K,V>(key, value, parent);
551 +        if (cmp < 0)
552 +            parent.left = e;
553 +        else
554 +            parent.right = e;
555 +        fixAfterInsertion(e);
556 +        size++;
557 +        modCount++;
558 +        return null;
559      }
560  
561      /**
562       * Removes the mapping for this key from this TreeMap if present.
563       *
564       * @param  key key for which mapping should be removed
565 <     * @return previous value associated with specified key, or <tt>null</tt>
566 <     *         if there was no mapping for key.  A <tt>null</tt> return can
567 <     *         also indicate that the map previously associated
568 <     *         <tt>null</tt> with the specified key.
569 <     *
570 <     * @throws    ClassCastException key cannot be compared with the keys
571 <     *            currently in the map.
572 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
573 <     *         natural order, or its comparator does not tolerate
603 <     *         <tt>null</tt> keys.
565 >     * @return the previous value associated with <tt>key</tt>, or
566 >     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
567 >     *         (A <tt>null</tt> return can also indicate that the map
568 >     *         previously associated <tt>null</tt> with <tt>key</tt>.)
569 >     * @throws ClassCastException if the specified key cannot be compared
570 >     *         with the keys currently in the map
571 >     * @throws NullPointerException if the specified key is null
572 >     *         and this map uses natural ordering, or its comparator
573 >     *         does not permit null keys
574       */
575      public V remove(Object key) {
576          Entry<K,V> p = getEntry(key);
# Line 613 | Line 583 | public class TreeMap<K,V>
583      }
584  
585      /**
586 <     * Removes all mappings from this TreeMap.
586 >     * Removes all of the mappings from this map.
587 >     * The map will be empty after this call returns.
588       */
589      public void clear() {
590          modCount++;
# Line 625 | Line 596 | public class TreeMap<K,V>
596       * Returns a shallow copy of this <tt>TreeMap</tt> instance. (The keys and
597       * values themselves are not cloned.)
598       *
599 <     * @return a shallow copy of this Map.
599 >     * @return a shallow copy of this map
600       */
601      public Object clone() {
602          TreeMap<K,V> clone = null;
# Line 640 | Line 611 | public class TreeMap<K,V>
611          clone.size = 0;
612          clone.modCount = 0;
613          clone.entrySet = null;
614 <        clone.descendingEntrySet = null;
615 <        clone.descendingKeySet = null;
614 >        clone.navigableKeySet = null;
615 >        clone.descendingMap = null;
616  
617          // Initialize clone with our mappings
618          try {
# Line 656 | Line 627 | public class TreeMap<K,V>
627      // NavigableMap API methods
628  
629      /**
630 <     * Returns a key-value mapping associated with the least
660 <     * key in this map, or <tt>null</tt> if the map is empty.
661 <     *
662 <     * @return an Entry with least key, or <tt>null</tt>
663 <     * if the map is empty.
630 >     * @since 1.6
631       */
632      public Map.Entry<K,V> firstEntry() {
633 <        Entry<K,V> e = getFirstEntry();
667 <        return (e == null)? null : new SnapshotEntry(e);
633 >        return exportEntry(getFirstEntry());
634      }
635  
636      /**
637 <     * Returns a key-value mapping associated with the greatest
672 <     * key in this map, or <tt>null</tt> if the map is empty.
673 <     * The returned entry does <em>not</em> support
674 <     * the <tt>Entry.setValue</tt> method.
675 <     *
676 <     * @return an Entry with greatest key, or <tt>null</tt>
677 <     * if the map is empty.
637 >     * @since 1.6
638       */
639      public Map.Entry<K,V> lastEntry() {
640 <        Entry<K,V> e = getLastEntry();
681 <        return (e == null)? null : new SnapshotEntry(e);
640 >        return exportEntry(getLastEntry());
641      }
642  
643      /**
644 <     * Removes and returns a key-value mapping associated with
686 <     * the least key in this map, or <tt>null</tt> if the map is empty.
687 <     *
688 <     * @return the removed first entry of this map, or <tt>null</tt>
689 <     * if the map is empty.
644 >     * @since 1.6
645       */
646      public Map.Entry<K,V> pollFirstEntry() {
647          Entry<K,V> p = getFirstEntry();
648 <        if (p == null)
649 <            return null;
650 <        Map.Entry result = new SnapshotEntry(p);
696 <        deleteEntry(p);
648 >        Map.Entry<K,V> result = exportEntry(p);
649 >        if (p != null)
650 >            deleteEntry(p);
651          return result;
652      }
653  
654      /**
655 <     * Removes and returns a key-value mapping associated with
702 <     * the greatest key in this map, or <tt>null</tt> if the map is empty.
703 <     *
704 <     * @return the removed last entry of this map, or <tt>null</tt>
705 <     * if the map is empty.
655 >     * @since 1.6
656       */
657      public Map.Entry<K,V> pollLastEntry() {
658          Entry<K,V> p = getLastEntry();
659 <        if (p == null)
660 <            return null;
661 <        Map.Entry result = new SnapshotEntry(p);
712 <        deleteEntry(p);
659 >        Map.Entry<K,V> result = exportEntry(p);
660 >        if (p != null)
661 >            deleteEntry(p);
662          return result;
663      }
664  
665      /**
666 <     * Returns a key-value mapping associated with the least key
667 <     * greater than or equal to the given key, or <tt>null</tt> if
668 <     * there is no such entry.
669 <     *
670 <     * @param key the key.
722 <     * @return an Entry associated with ceiling of given key, or
723 <     * <tt>null</tt> if there is no such Entry.
724 <     * @throws ClassCastException if key cannot be compared with the
725 <     * keys currently in the map.
726 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
727 <     *         natural order, or its comparator does not tolerate
728 <     *         <tt>null</tt> keys.
666 >     * @throws ClassCastException {@inheritDoc}
667 >     * @throws NullPointerException if the specified key is null
668 >     *         and this map uses natural ordering, or its comparator
669 >     *         does not permit null keys
670 >     * @since 1.6
671       */
672 <    public Map.Entry<K,V> ceilingEntry(K key) {
673 <        Entry<K,V> e = getCeilingEntry(key);
732 <        return (e == null)? null : new SnapshotEntry(e);
672 >    public Map.Entry<K,V> lowerEntry(K key) {
673 >        return exportEntry(getLowerEntry(key));
674      }
675  
735
676      /**
677 <     * Returns least key greater than or equal to the given key, or
678 <     * <tt>null</tt> if there is no such key.
679 <     *
680 <     * @param key the key.
681 <     * @return the ceiling key, or <tt>null</tt>
742 <     * if there is no such key.
743 <     * @throws ClassCastException if key cannot be compared with the keys
744 <     *            currently in the map.
745 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
746 <     *         natural order, or its comparator does not tolerate
747 <     *         <tt>null</tt> keys.
677 >     * @throws ClassCastException {@inheritDoc}
678 >     * @throws NullPointerException if the specified key is null
679 >     *         and this map uses natural ordering, or its comparator
680 >     *         does not permit null keys
681 >     * @since 1.6
682       */
683 <    public K ceilingKey(K key) {
684 <        Entry<K,V> e = getCeilingEntry(key);
751 <        return (e == null)? null : e.key;
683 >    public K lowerKey(K key) {
684 >        return keyOrNull(getLowerEntry(key));
685      }
686  
754
755
687      /**
688 <     * Returns a key-value mapping associated with the greatest key
689 <     * less than or equal to the given key, or <tt>null</tt> if there
690 <     * is no such entry.
691 <     *
692 <     * @param key the key.
762 <     * @return an Entry associated with floor of given key, or <tt>null</tt>
763 <     * if there is no such Entry.
764 <     * @throws ClassCastException if key cannot be compared with the keys
765 <     *            currently in the map.
766 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
767 <     *         natural order, or its comparator does not tolerate
768 <     *         <tt>null</tt> keys.
688 >     * @throws ClassCastException {@inheritDoc}
689 >     * @throws NullPointerException if the specified key is null
690 >     *         and this map uses natural ordering, or its comparator
691 >     *         does not permit null keys
692 >     * @since 1.6
693       */
694      public Map.Entry<K,V> floorEntry(K key) {
695 <        Entry<K,V> e = getFloorEntry(key);
772 <        return (e == null)? null : new SnapshotEntry(e);
695 >        return exportEntry(getFloorEntry(key));
696      }
697  
698      /**
699 <     * Returns the greatest key
700 <     * less than or equal to the given key, or <tt>null</tt> if there
701 <     * is no such key.
702 <     *
703 <     * @param key the key.
781 <     * @return the floor of given key, or <tt>null</tt> if there is no
782 <     * such key.
783 <     * @throws ClassCastException if key cannot be compared with the keys
784 <     *            currently in the map.
785 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
786 <     *         natural order, or its comparator does not tolerate
787 <     *         <tt>null</tt> keys.
699 >     * @throws ClassCastException {@inheritDoc}
700 >     * @throws NullPointerException if the specified key is null
701 >     *         and this map uses natural ordering, or its comparator
702 >     *         does not permit null keys
703 >     * @since 1.6
704       */
705      public K floorKey(K key) {
706 <        Entry<K,V> e = getFloorEntry(key);
791 <        return (e == null)? null : e.key;
706 >        return keyOrNull(getFloorEntry(key));
707      }
708  
709      /**
710 <     * Returns a key-value mapping associated with the least key
711 <     * strictly greater than the given key, or <tt>null</tt> if there
712 <     * is no such entry.
713 <     *
714 <     * @param key the key.
800 <     * @return an Entry with least key greater than the given key, or
801 <     * <tt>null</tt> if there is no such Entry.
802 <     * @throws ClassCastException if key cannot be compared with the keys
803 <     *            currently in the map.
804 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
805 <     *         natural order, or its comparator does not tolerate
806 <     *         <tt>null</tt> keys.
710 >     * @throws ClassCastException {@inheritDoc}
711 >     * @throws NullPointerException if the specified key is null
712 >     *         and this map uses natural ordering, or its comparator
713 >     *         does not permit null keys
714 >     * @since 1.6
715       */
716 <    public Map.Entry<K,V> higherEntry(K key) {
717 <        Entry<K,V> e = getHigherEntry(key);
810 <        return (e == null)? null : new SnapshotEntry(e);
716 >    public Map.Entry<K,V> ceilingEntry(K key) {
717 >        return exportEntry(getCeilingEntry(key));
718      }
719  
720      /**
721 <     * Returns the least key strictly greater than the given key, or
722 <     * <tt>null</tt> if there is no such key.
723 <     *
724 <     * @param key the key.
725 <     * @return the least key greater than the given key, or
819 <     * <tt>null</tt> if there is no such key.
820 <     * @throws ClassCastException if key cannot be compared with the keys
821 <     *            currently in the map.
822 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
823 <     *         natural order, or its comparator does not tolerate
824 <     *         <tt>null</tt> keys.
721 >     * @throws ClassCastException {@inheritDoc}
722 >     * @throws NullPointerException if the specified key is null
723 >     *         and this map uses natural ordering, or its comparator
724 >     *         does not permit null keys
725 >     * @since 1.6
726       */
727 <    public K higherKey(K key) {
728 <        Entry<K,V> e = getHigherEntry(key);
828 <        return (e == null)? null : e.key;
727 >    public K ceilingKey(K key) {
728 >        return keyOrNull(getCeilingEntry(key));
729      }
730  
731      /**
732 <     * Returns a key-value mapping associated with the greatest
733 <     * key strictly less than the given key, or <tt>null</tt> if there is no
734 <     * such entry.
735 <     *
736 <     * @param key the key.
837 <     * @return an Entry with greatest key less than the given
838 <     * key, or <tt>null</tt> if there is no such Entry.
839 <     * @throws ClassCastException if key cannot be compared with the keys
840 <     *            currently in the map.
841 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
842 <     *         natural order, or its comparator does not tolerate
843 <     *         <tt>null</tt> keys.
732 >     * @throws ClassCastException {@inheritDoc}
733 >     * @throws NullPointerException if the specified key is null
734 >     *         and this map uses natural ordering, or its comparator
735 >     *         does not permit null keys
736 >     * @since 1.6
737       */
738 <    public Map.Entry<K,V> lowerEntry(K key) {
739 <        Entry<K,V> e =  getLowerEntry(key);
847 <        return (e == null)? null : new SnapshotEntry(e);
738 >    public Map.Entry<K,V> higherEntry(K key) {
739 >        return exportEntry(getHigherEntry(key));
740      }
741  
742      /**
743 <     * Returns the greatest key strictly less than the given key, or
744 <     * <tt>null</tt> if there is no such key.
745 <     *
746 <     * @param key the key.
747 <     * @return the greatest key less than the given
856 <     * key, or <tt>null</tt> if there is no such key.
857 <     * @throws ClassCastException if key cannot be compared with the keys
858 <     *            currently in the map.
859 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
860 <     *         natural order, or its comparator does not tolerate
861 <     *         <tt>null</tt> keys.
743 >     * @throws ClassCastException {@inheritDoc}
744 >     * @throws NullPointerException if the specified key is null
745 >     *         and this map uses natural ordering, or its comparator
746 >     *         does not permit null keys
747 >     * @since 1.6
748       */
749 <    public K lowerKey(K key) {
750 <        Entry<K,V> e =  getLowerEntry(key);
865 <        return (e == null)? null : e.key;
749 >    public K higherKey(K key) {
750 >        return keyOrNull(getHigherEntry(key));
751      }
752  
753      // Views
# Line 872 | Line 757 | public class TreeMap<K,V>
757       * the first time this view is requested.  Views are stateless, so
758       * there's no reason to create more than one.
759       */
760 <    private transient Set<Map.Entry<K,V>> entrySet = null;
761 <    private transient Set<Map.Entry<K,V>> descendingEntrySet = null;
762 <    private transient Set<K> descendingKeySet = null;
763 <
764 <    transient Set<K> keySet = null;        // XXX remove when integrated
765 <    transient Collection<V> values = null; // XXX remove when integrated
766 <
767 <    /**
768 <     * Returns a Set view of the keys contained in this map.  The set's
769 <     * iterator will return the keys in ascending order.  The set is backed by
770 <     * this <tt>TreeMap</tt> instance, so changes to this map are reflected in
771 <     * the Set, and vice-versa.  The Set supports element removal, which
772 <     * removes the corresponding mapping from the map, via the
773 <     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>,
774 <     * <tt>retainAll</tt>, and <tt>clear</tt> operations.  It does not support
775 <     * the <tt>add</tt> or <tt>addAll</tt> operations.
776 <     *
892 <     * @return a set view of the keys contained in this TreeMap.
760 >    private transient EntrySet entrySet = null;
761 >    private transient KeySet<K> navigableKeySet = null;
762 >    private transient NavigableMap<K,V> descendingMap = null;
763 >
764 >    /**
765 >     * Returns a {@link Set} view of the keys contained in this map.
766 >     * The set's iterator returns the keys in ascending order.
767 >     * The set is backed by the map, so changes to the map are
768 >     * reflected in the set, and vice-versa.  If the map is modified
769 >     * while an iteration over the set is in progress (except through
770 >     * the iterator's own <tt>remove</tt> operation), the results of
771 >     * the iteration are undefined.  The set supports element removal,
772 >     * which removes the corresponding mapping from the map, via the
773 >     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
774 >     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
775 >     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
776 >     * operations.
777       */
778      public Set<K> keySet() {
779 <        Set<K> ks = keySet;
896 <        return (ks != null) ? ks : (keySet = new KeySet());
779 >        return navigableKeySet();
780      }
781  
782 <    class KeySet extends AbstractSet<K> {
783 <        public Iterator<K> iterator() {
784 <            return new KeyIterator(getFirstEntry());
785 <        }
786 <        
787 <        public int size() {
905 <            return TreeMap.this.size();
906 <        }
907 <        
908 <        public boolean contains(Object o) {
909 <            return containsKey(o);
910 <        }
911 <        
912 <        public boolean remove(Object o) {
913 <            int oldSize = size;
914 <            TreeMap.this.remove(o);
915 <            return size != oldSize;
916 <        }
917 <        
918 <        public void clear() {
919 <            TreeMap.this.clear();
920 <        }
782 >    /**
783 >     * @since 1.6
784 >     */
785 >    public NavigableSet<K> navigableKeySet() {
786 >        KeySet<K> nks = navigableKeySet;
787 >        return (nks != null) ? nks : (navigableKeySet = new KeySet(this));
788      }
789  
790      /**
791 <     * Returns a collection view of the values contained in this map.  The
792 <     * collection's iterator will return the values in the order that their
793 <     * corresponding keys appear in the tree.  The collection is backed by
794 <     * this <tt>TreeMap</tt> instance, so changes to this map are reflected in
795 <     * the collection, and vice-versa.  The collection supports element
796 <     * removal, which removes the corresponding mapping from the map through
797 <     * the <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
798 <     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
799 <     * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
800 <     *
801 <     * @return a collection view of the values contained in this map.
791 >     * @since 1.6
792 >     */
793 >    public NavigableSet<K> descendingKeySet() {
794 >        return descendingMap().navigableKeySet();
795 >    }
796 >
797 >    /**
798 >     * Returns a {@link Collection} view of the values contained in this map.
799 >     * The collection's iterator returns the values in ascending order
800 >     * of the corresponding keys.
801 >     * The collection is backed by the map, so changes to the map are
802 >     * reflected in the collection, and vice-versa.  If the map is
803 >     * modified while an iteration over the collection is in progress
804 >     * (except through the iterator's own <tt>remove</tt> operation),
805 >     * the results of the iteration are undefined.  The collection
806 >     * supports element removal, which removes the corresponding
807 >     * mapping from the map, via the <tt>Iterator.remove</tt>,
808 >     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
809 >     * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
810 >     * support the <tt>add</tt> or <tt>addAll</tt> operations.
811       */
812      public Collection<V> values() {
813          Collection<V> vs = values;
814          return (vs != null) ? vs : (values = new Values());
815      }
816  
817 +    /**
818 +     * Returns a {@link Set} view of the mappings contained in this map.
819 +     * The set's iterator returns the entries in ascending key order.
820 +     * The set is backed by the map, so changes to the map are
821 +     * reflected in the set, and vice-versa.  If the map is modified
822 +     * while an iteration over the set is in progress (except through
823 +     * the iterator's own <tt>remove</tt> operation, or through the
824 +     * <tt>setValue</tt> operation on a map entry returned by the
825 +     * iterator) the results of the iteration are undefined.  The set
826 +     * supports element removal, which removes the corresponding
827 +     * mapping from the map, via the <tt>Iterator.remove</tt>,
828 +     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
829 +     * <tt>clear</tt> operations.  It does not support the
830 +     * <tt>add</tt> or <tt>addAll</tt> operations.
831 +     */
832 +    public Set<Map.Entry<K,V>> entrySet() {
833 +        EntrySet es = entrySet;
834 +        return (es != null) ? es : (entrySet = new EntrySet());
835 +    }
836 +
837 +    /**
838 +     * @since 1.6
839 +     */
840 +    public NavigableMap<K, V> descendingMap() {
841 +        NavigableMap<K, V> km = descendingMap;
842 +        return (km != null) ? km :
843 +            (descendingMap = new DescendingSubMap(this,
844 +                                                  true, null, true,
845 +                                                  true, null, true));
846 +    }
847 +
848 +    /**
849 +     * @throws ClassCastException       {@inheritDoc}
850 +     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
851 +     *         null and this map uses natural ordering, or its comparator
852 +     *         does not permit null keys
853 +     * @throws IllegalArgumentException {@inheritDoc}
854 +     * @since 1.6
855 +     */
856 +    public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
857 +                                    K toKey,   boolean toInclusive) {
858 +        return new AscendingSubMap(this,
859 +                                   false, fromKey, fromInclusive,
860 +                                   false, toKey,   toInclusive);
861 +    }
862 +
863 +    /**
864 +     * @throws ClassCastException       {@inheritDoc}
865 +     * @throws NullPointerException if <tt>toKey</tt> is null
866 +     *         and this map uses natural ordering, or its comparator
867 +     *         does not permit null keys
868 +     * @throws IllegalArgumentException {@inheritDoc}
869 +     * @since 1.6
870 +     */
871 +    public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
872 +        return new AscendingSubMap(this,
873 +                                   true,  null,  true,
874 +                                   false, toKey, inclusive);
875 +    }
876 +
877 +    /**
878 +     * @throws ClassCastException       {@inheritDoc}
879 +     * @throws NullPointerException if <tt>fromKey</tt> is null
880 +     *         and this map uses natural ordering, or its comparator
881 +     *         does not permit null keys
882 +     * @throws IllegalArgumentException {@inheritDoc}
883 +     * @since 1.6
884 +     */
885 +    public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
886 +        return new AscendingSubMap(this,
887 +                                   false, fromKey, inclusive,
888 +                                   true,  null,    true);
889 +    }
890 +
891 +    /**
892 +     * @throws ClassCastException       {@inheritDoc}
893 +     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
894 +     *         null and this map uses natural ordering, or its comparator
895 +     *         does not permit null keys
896 +     * @throws IllegalArgumentException {@inheritDoc}
897 +     */
898 +    public SortedMap<K,V> subMap(K fromKey, K toKey) {
899 +        return subMap(fromKey, true, toKey, false);
900 +    }
901 +
902 +    /**
903 +     * @throws ClassCastException       {@inheritDoc}
904 +     * @throws NullPointerException if <tt>toKey</tt> is null
905 +     *         and this map uses natural ordering, or its comparator
906 +     *         does not permit null keys
907 +     * @throws IllegalArgumentException {@inheritDoc}
908 +     */
909 +    public SortedMap<K,V> headMap(K toKey) {
910 +        return headMap(toKey, false);
911 +    }
912 +
913 +    /**
914 +     * @throws ClassCastException       {@inheritDoc}
915 +     * @throws NullPointerException if <tt>fromKey</tt> is null
916 +     *         and this map uses natural ordering, or its comparator
917 +     *         does not permit null keys
918 +     * @throws IllegalArgumentException {@inheritDoc}
919 +     */
920 +    public SortedMap<K,V> tailMap(K fromKey) {
921 +        return tailMap(fromKey, true);
922 +    }
923 +
924 +    // View class support
925 +
926      class Values extends AbstractCollection<V> {
927          public Iterator<V> iterator() {
928              return new ValueIterator(getFirstEntry());
929          }
930 <        
930 >
931          public int size() {
932              return TreeMap.this.size();
933          }
934 <        
934 >
935          public boolean contains(Object o) {
936 <            for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
952 <                if (valEquals(e.getValue(), o))
953 <                    return true;
954 <            return false;
936 >            return TreeMap.this.containsValue(o);
937          }
938 <        
938 >
939          public boolean remove(Object o) {
940              for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
941                  if (valEquals(e.getValue(), o)) {
# Line 963 | Line 945 | public class TreeMap<K,V>
945              }
946              return false;
947          }
948 <        
948 >
949          public void clear() {
950              TreeMap.this.clear();
951          }
952      }
953  
972    /**
973     * Returns a set view of the mappings contained in this map.  The set's
974     * iterator returns the mappings in ascending key order.  Each element in
975     * the returned set is a <tt>Map.Entry</tt>.  The set is backed by this
976     * map, so changes to this map are reflected in the set, and vice-versa.
977     * The set supports element removal, which removes the corresponding
978     * mapping from the TreeMap, through the <tt>Iterator.remove</tt>,
979     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
980     * <tt>clear</tt> operations.  It does not support the <tt>add</tt> or
981     * <tt>addAll</tt> operations.
982     *
983     * @return a set view of the mappings contained in this map.
984     * @see Map.Entry
985     */
986    public Set<Map.Entry<K,V>> entrySet() {
987        Set<Map.Entry<K,V>> es = entrySet;
988        return (es != null) ? es : (entrySet = new EntrySet());
989    }
990
954      class EntrySet extends AbstractSet<Map.Entry<K,V>> {
955          public Iterator<Map.Entry<K,V>> iterator() {
956              return new EntryIterator(getFirstEntry());
957          }
958 <        
958 >
959          public boolean contains(Object o) {
960              if (!(o instanceof Map.Entry))
961                  return false;
# Line 1001 | Line 964 | public class TreeMap<K,V>
964              Entry<K,V> p = getEntry(entry.getKey());
965              return p != null && valEquals(p.getValue(), value);
966          }
967 <        
967 >
968          public boolean remove(Object o) {
969              if (!(o instanceof Map.Entry))
970                  return false;
# Line 1014 | Line 977 | public class TreeMap<K,V>
977              }
978              return false;
979          }
980 <        
980 >
981          public int size() {
982              return TreeMap.this.size();
983          }
984 <        
984 >
985          public void clear() {
986              TreeMap.this.clear();
987          }
988      }
989  
990 <    /**
991 <     * Returns a set view of the mappings contained in this map.  The
992 <     * set's iterator returns the mappings in descrending key order.
993 <     * Each element in the returned set is a <tt>Map.Entry</tt>.  The
994 <     * set is backed by this map, so changes to this map are reflected
995 <     * in the set, and vice-versa.  The set supports element removal,
996 <     * which removes the corresponding mapping from the TreeMap,
997 <     * through the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
998 <     * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
999 <     * operations.  It does not support the <tt>add</tt> or
1037 <     * <tt>addAll</tt> operations.
1038 <     *
1039 <     * @return a set view of the mappings contained in this map, in
1040 <     * descending key order
1041 <     * @see Map.Entry
1042 <     */
1043 <    public Set<Map.Entry<K,V>> descendingEntrySet() {
1044 <        Set<Map.Entry<K,V>> es = descendingEntrySet;
1045 <        return (es != null) ? es : (descendingEntrySet = new DescendingEntrySet());
990 >    /*
991 >     * Unlike Values and EntrySet, the KeySet class is static,
992 >     * delegating to a NavigableMap to allow use by SubMaps, which
993 >     * outweighs the ugliness of needing type-tests for the following
994 >     * Iterator methods that are defined appropriately in main versus
995 >     * submap classes.
996 >     */
997 >
998 >    Iterator<K> keyIterator() {
999 >        return new KeyIterator(getFirstEntry());
1000      }
1001  
1002 <    class DescendingEntrySet extends EntrySet {
1003 <        public Iterator<Map.Entry<K,V>> iterator() {
1004 <            return new DescendingEntryIterator(getLastEntry());
1002 >    Iterator<K> descendingKeyIterator() {
1003 >        return new DescendingKeyIterator(getFirstEntry());
1004 >    }
1005 >
1006 >    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
1007 >        private final NavigableMap<E, Object> m;
1008 >        KeySet(NavigableMap<E,Object> map) { m = map; }
1009 >
1010 >        public Iterator<E> iterator() {
1011 >            if (m instanceof TreeMap)
1012 >                return ((TreeMap<E,Object>)m).keyIterator();
1013 >            else
1014 >                return (Iterator<E>)(((TreeMap.NavigableSubMap)m).keyIterator());
1015 >        }
1016 >
1017 >        public Iterator<E> descendingIterator() {
1018 >            if (m instanceof TreeMap)
1019 >                return ((TreeMap<E,Object>)m).descendingKeyIterator();
1020 >            else
1021 >                return (Iterator<E>)(((TreeMap.NavigableSubMap)m).descendingKeyIterator());
1022 >        }
1023 >
1024 >        public int size() { return m.size(); }
1025 >        public boolean isEmpty() { return m.isEmpty(); }
1026 >        public boolean contains(Object o) { return m.containsKey(o); }
1027 >        public void clear() { m.clear(); }
1028 >        public E lower(E e) { return m.lowerKey(e); }
1029 >        public E floor(E e) { return m.floorKey(e); }
1030 >        public E ceiling(E e) { return m.ceilingKey(e); }
1031 >        public E higher(E e) { return m.higherKey(e); }
1032 >        public E first() { return m.firstKey(); }
1033 >        public E last() { return m.lastKey(); }
1034 >        public Comparator<? super E> comparator() { return m.comparator(); }
1035 >        public E pollFirst() {
1036 >            Map.Entry<E,Object> e = m.pollFirstEntry();
1037 >            return e == null? null : e.getKey();
1038 >        }
1039 >        public E pollLast() {
1040 >            Map.Entry<E,Object> e = m.pollLastEntry();
1041 >            return e == null? null : e.getKey();
1042 >        }
1043 >        public boolean remove(Object o) {
1044 >            int oldSize = size();
1045 >            m.remove(o);
1046 >            return size() != oldSize;
1047 >        }
1048 >        public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
1049 >                                      E toElement, boolean toInclusive) {
1050 >            return new TreeSet<E>(m.subMap(fromElement, fromInclusive,
1051 >                                           toElement,   toInclusive));
1052 >        }
1053 >        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1054 >            return new TreeSet<E>(m.headMap(toElement, inclusive));
1055 >        }
1056 >        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1057 >            return new TreeSet<E>(m.tailMap(fromElement, inclusive));
1058 >        }
1059 >        public SortedSet<E> subSet(E fromElement, E toElement) {
1060 >            return subSet(fromElement, true, toElement, false);
1061 >        }
1062 >        public SortedSet<E> headSet(E toElement) {
1063 >            return headSet(toElement, false);
1064 >        }
1065 >        public SortedSet<E> tailSet(E fromElement) {
1066 >            return tailSet(fromElement, true);
1067 >        }
1068 >        public NavigableSet<E> descendingSet() {
1069 >            return new TreeSet(m.descendingMap());
1070          }
1071      }
1072  
1073      /**
1074 <     * Returns a Set view of the keys contained in this map.  The
1056 <     * set's iterator will return the keys in descending order.  The
1057 <     * map is backed by this <tt>TreeMap</tt> instance, so changes to
1058 <     * this map are reflected in the Set, and vice-versa.  The Set
1059 <     * supports element removal, which removes the corresponding
1060 <     * mapping from the map, via the <tt>Iterator.remove</tt>,
1061 <     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>,
1062 <     * and <tt>clear</tt> operations.  It does not support the
1063 <     * <tt>add</tt> or <tt>addAll</tt> operations.
1064 <     *
1065 <     * @return a set view of the keys contained in this TreeMap.
1074 >     * Base class for TreeMap Iterators
1075       */
1076 <    public Set<K> descendingKeySet() {
1077 <        Set<K> ks = descendingKeySet;
1078 <        return (ks != null) ? ks : (descendingKeySet = new DescendingKeySet());
1079 <    }
1080 <
1081 <    class DescendingKeySet extends KeySet {
1082 <        public Iterator<K> iterator() {
1083 <            return new DescendingKeyIterator(getLastEntry());
1076 >    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1077 >        Entry<K,V> next;
1078 >        Entry<K,V> lastReturned;
1079 >        int expectedModCount;
1080 >
1081 >        PrivateEntryIterator(Entry<K,V> first) {
1082 >            expectedModCount = modCount;
1083 >            lastReturned = null;
1084 >            next = first;
1085 >        }
1086 >
1087 >        public final boolean hasNext() {
1088 >            return next != null;
1089 >        }
1090 >
1091 >        final Entry<K,V> nextEntry() {
1092 >            Entry<K,V> e = lastReturned = next;
1093 >            if (e == null)
1094 >                throw new NoSuchElementException();
1095 >            if (modCount != expectedModCount)
1096 >                throw new ConcurrentModificationException();
1097 >            next = successor(e);
1098 >            return e;
1099 >        }
1100 >
1101 >        final Entry<K,V> prevEntry() {
1102 >            Entry<K,V> e = lastReturned= next;
1103 >            if (e == null)
1104 >                throw new NoSuchElementException();
1105 >            if (modCount != expectedModCount)
1106 >                throw new ConcurrentModificationException();
1107 >            next = predecessor(e);
1108 >            return e;
1109 >        }
1110 >
1111 >        public void remove() {
1112 >            if (lastReturned == null)
1113 >                throw new IllegalStateException();
1114 >            if (modCount != expectedModCount)
1115 >                throw new ConcurrentModificationException();
1116 >            if (lastReturned.left != null && lastReturned.right != null)
1117 >                next = lastReturned;
1118 >            deleteEntry(lastReturned);
1119 >            expectedModCount++;
1120 >            lastReturned = null;
1121 >        }
1122 >    }
1123 >
1124 >    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1125 >        EntryIterator(Entry<K,V> first) {
1126 >            super(first);
1127 >        }
1128 >        public Map.Entry<K,V> next() {
1129 >            return nextEntry();
1130 >        }
1131 >    }
1132 >
1133 >    final class ValueIterator extends PrivateEntryIterator<V> {
1134 >        ValueIterator(Entry<K,V> first) {
1135 >            super(first);
1136 >        }
1137 >        public V next() {
1138 >            return nextEntry().value;
1139 >        }
1140 >    }
1141 >
1142 >    final class KeyIterator extends PrivateEntryIterator<K> {
1143 >        KeyIterator(Entry<K,V> first) {
1144 >            super(first);
1145 >        }
1146 >        public K next() {
1147 >            return nextEntry().key;
1148          }
1149      }
1150  
1151 +    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1152 +        DescendingKeyIterator(Entry<K,V> first) {
1153 +            super(first);
1154 +        }
1155 +        public K next() {
1156 +            return prevEntry().key;
1157 +        }
1158 +    }
1159 +
1160 +    // Little utilities
1161 +
1162      /**
1163 <     * Returns a view of the portion of this map whose keys range from
1080 <     * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive.  (If
1081 <     * <tt>fromKey</tt> and <tt>toKey</tt> are equal, the returned sorted map
1082 <     * is empty.)  The returned sorted map is backed by this map, so changes
1083 <     * in the returned sorted map are reflected in this map, and vice-versa.
1084 <     * The returned sorted map supports all optional map operations.<p>
1085 <     *
1086 <     * The sorted map returned by this method will throw an
1087 <     * <tt>IllegalArgumentException</tt> if the user attempts to insert a key
1088 <     * less than <tt>fromKey</tt> or greater than or equal to
1089 <     * <tt>toKey</tt>.<p>
1090 <     *
1091 <     * Note: this method always returns a <i>half-open range</i> (which
1092 <     * includes its low endpoint but not its high endpoint).  If you need a
1093 <     * <i>closed range</i> (which includes both endpoints), and the key type
1094 <     * allows for calculation of the successor a given key, merely request the
1095 <     * subrange from <tt>lowEndpoint</tt> to <tt>successor(highEndpoint)</tt>.
1096 <     * For example, suppose that <tt>m</tt> is a sorted map whose keys are
1097 <     * strings.  The following idiom obtains a view containing all of the
1098 <     * key-value mappings in <tt>m</tt> whose keys are between <tt>low</tt>
1099 <     * and <tt>high</tt>, inclusive:
1100 <     *             <pre>    NavigableMap sub = m.submap(low, high+"\0");</pre>
1101 <     * A similar technique can be used to generate an <i>open range</i> (which
1102 <     * contains neither endpoint).  The following idiom obtains a view
1103 <     * containing all of the key-value mappings in <tt>m</tt> whose keys are
1104 <     * between <tt>low</tt> and <tt>high</tt>, exclusive:
1105 <     *             <pre>    NavigableMap sub = m.subMap(low+"\0", high);</pre>
1106 <     *
1107 <     * @param fromKey low endpoint (inclusive) of the subMap.
1108 <     * @param toKey high endpoint (exclusive) of the subMap.
1109 <     *
1110 <     * @return a view of the portion of this map whose keys range from
1111 <     *                <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive.
1112 <     *
1113 <     * @throws ClassCastException if <tt>fromKey</tt> and <tt>toKey</tt>
1114 <     *         cannot be compared to one another using this map's comparator
1115 <     *         (or, if the map has no comparator, using natural ordering).
1116 <     * @throws IllegalArgumentException if <tt>fromKey</tt> is greater than
1117 <     *         <tt>toKey</tt>.
1118 <     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
1119 <     *               <tt>null</tt> and this map uses natural order, or its
1120 <     *               comparator does not tolerate <tt>null</tt> keys.
1163 >     * Compares two keys using the correct comparison method for this TreeMap.
1164       */
1165 <    public NavigableMap<K,V> subMap(K fromKey, K toKey) {
1166 <        return new SubMap(fromKey, toKey);
1165 >    final int compare(Object k1, Object k2) {
1166 >        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1167 >            : comparator.compare((K)k1, (K)k2);
1168      }
1169  
1170      /**
1171 <     * Returns a view of the portion of this map whose keys are strictly less
1172 <     * than <tt>toKey</tt>.  The returned sorted map is backed by this map, so
1173 <     * changes in the returned sorted map are reflected in this map, and
1174 <     * vice-versa.  The returned sorted map supports all optional map
1175 <     * operations.<p>
1176 <     *
1133 <     * The sorted map returned by this method will throw an
1134 <     * <tt>IllegalArgumentException</tt> if the user attempts to insert a key
1135 <     * greater than or equal to <tt>toKey</tt>.<p>
1136 <     *
1137 <     * Note: this method always returns a view that does not contain its
1138 <     * (high) endpoint.  If you need a view that does contain this endpoint,
1139 <     * and the key type allows for calculation of the successor a given key,
1140 <     * merely request a headMap bounded by <tt>successor(highEndpoint)</tt>.
1141 <     * For example, suppose that suppose that <tt>m</tt> is a sorted map whose
1142 <     * keys are strings.  The following idiom obtains a view containing all of
1143 <     * the key-value mappings in <tt>m</tt> whose keys are less than or equal
1144 <     * to <tt>high</tt>:
1145 <     * <pre>
1146 <     *     NavigableMap head = m.headMap(high+"\0");
1147 <     * </pre>
1148 <     *
1149 <     * @param toKey high endpoint (exclusive) of the headMap.
1150 <     * @return a view of the portion of this map whose keys are strictly
1151 <     *                less than <tt>toKey</tt>.
1152 <     *
1153 <     * @throws ClassCastException if <tt>toKey</tt> is not compatible
1154 <     *         with this map's comparator (or, if the map has no comparator,
1155 <     *         if <tt>toKey</tt> does not implement <tt>Comparable</tt>).
1156 <     * @throws IllegalArgumentException if this map is itself a subMap,
1157 <     *         headMap, or tailMap, and <tt>toKey</tt> is not within the
1158 <     *         specified range of the subMap, headMap, or tailMap.
1159 <     * @throws NullPointerException if <tt>toKey</tt> is <tt>null</tt> and
1160 <     *               this map uses natural order, or its comparator does not
1161 <     *               tolerate <tt>null</tt> keys.
1162 <     */
1163 <    public NavigableMap<K,V> headMap(K toKey) {
1164 <        return new SubMap(toKey, true);
1165 <    }
1166 <
1167 <    /**
1168 <     * Returns a view of the portion of this map whose keys are greater than
1169 <     * or equal to <tt>fromKey</tt>.  The returned sorted map is backed by
1170 <     * this map, so changes in the returned sorted map are reflected in this
1171 <     * map, and vice-versa.  The returned sorted map supports all optional map
1172 <     * operations.<p>
1173 <     *
1174 <     * The sorted map returned by this method will throw an
1175 <     * <tt>IllegalArgumentException</tt> if the user attempts to insert a key
1176 <     * less than <tt>fromKey</tt>.<p>
1177 <     *
1178 <     * Note: this method always returns a view that contains its (low)
1179 <     * endpoint.  If you need a view that does not contain this endpoint, and
1180 <     * the element type allows for calculation of the successor a given value,
1181 <     * merely request a tailMap bounded by <tt>successor(lowEndpoint)</tt>.
1182 <     * For example, suppose that <tt>m</tt> is a sorted map whose keys
1183 <     * are strings.  The following idiom obtains a view containing
1184 <     * all of the key-value mappings in <tt>m</tt> whose keys are strictly
1185 <     * greater than <tt>low</tt>: <pre>
1186 <     *     NavigableMap tail = m.tailMap(low+"\0");
1187 <     * </pre>
1188 <     *
1189 <     * @param fromKey low endpoint (inclusive) of the tailMap.
1190 <     * @return a view of the portion of this map whose keys are greater
1191 <     *                than or equal to <tt>fromKey</tt>.
1192 <     * @throws ClassCastException if <tt>fromKey</tt> is not compatible
1193 <     *         with this map's comparator (or, if the map has no comparator,
1194 <     *         if <tt>fromKey</tt> does not implement <tt>Comparable</tt>).
1195 <     * @throws IllegalArgumentException if this map is itself a subMap,
1196 <     *         headMap, or tailMap, and <tt>fromKey</tt> is not within the
1197 <     *         specified range of the subMap, headMap, or tailMap.
1198 <     * @throws NullPointerException if <tt>fromKey</tt> is <tt>null</tt> and
1199 <     *               this map uses natural order, or its comparator does not
1200 <     *               tolerate <tt>null</tt> keys.
1201 <     */
1202 <    public NavigableMap<K,V> tailMap(K fromKey) {
1203 <        return new SubMap(fromKey, false);
1204 <    }
1205 <
1206 <    private class SubMap
1207 <        extends AbstractMap<K,V>
1208 <        implements NavigableMap<K,V>, java.io.Serializable {
1209 <        private static final long serialVersionUID = -6520786458950516097L;
1171 >     * Test two values for equality.  Differs from o1.equals(o2) only in
1172 >     * that it copes with <tt>null</tt> o1 properly.
1173 >     */
1174 >    final static boolean valEquals(Object o1, Object o2) {
1175 >        return (o1==null ? o2==null : o1.equals(o2));
1176 >    }
1177  
1178 <        /**
1179 <         * fromKey is significant only if fromStart is false.  Similarly,
1180 <         * toKey is significant only if toStart is false.
1178 >    /**
1179 >     * Return SimpleImmutableEntry for entry, or null if null
1180 >     */
1181 >    static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
1182 >        return e == null? null :
1183 >            new AbstractMap.SimpleImmutableEntry<K,V>(e);
1184 >    }
1185 >
1186 >    /**
1187 >     * Return key for entry, or null if null
1188 >     */
1189 >    static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
1190 >        return e == null? null : e.key;
1191 >    }
1192 >
1193 >    /**
1194 >     * Returns the key corresponding to the specified Entry.
1195 >     * @throws NoSuchElementException if the Entry is null
1196 >     */
1197 >    static <K> K key(Entry<K,?> e) {
1198 >        if (e==null)
1199 >            throw new NoSuchElementException();
1200 >        return e.key;
1201 >    }
1202 >
1203 >
1204 >    // SubMaps
1205 >
1206 >    static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
1207 >        implements NavigableMap<K,V>, java.io.Serializable {
1208 >        /*
1209 >         * The backing map.
1210           */
1211 <        private boolean fromStart = false, toEnd = false;
1216 <        private K fromKey, toKey;
1211 >        final TreeMap<K,V> m;
1212  
1213 <        SubMap(K fromKey, K toKey) {
1214 <            if (compare(fromKey, toKey) > 0)
1215 <                throw new IllegalArgumentException("fromKey > toKey");
1216 <            this.fromKey = fromKey;
1217 <            this.toKey = toKey;
1218 <        }
1213 >        /*
1214 >         * Endpoints are represented as triples (fromStart, lo,
1215 >         * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is
1216 >         * true, then the low (absolute) bound is the start of the
1217 >         * backing map, and the other values are ignored. Otherwise,
1218 >         * if loInclusive is true, lo is the inclusive bound, else lo
1219 >         * is the exclusive bound. Similarly for the upper bound.
1220 >         */
1221  
1222 <        SubMap(K key, boolean headMap) {
1223 <            compare(key, key); // Type-check key
1224 <
1225 <            if (headMap) {
1226 <                fromStart = true;
1227 <                toKey = key;
1222 >        final K lo, hi;
1223 >        final boolean fromStart, toEnd;
1224 >        final boolean loInclusive, hiInclusive;
1225 >
1226 >        NavigableSubMap(TreeMap<K,V> m,
1227 >                        boolean fromStart, K lo, boolean loInclusive,
1228 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1229 >            if (!fromStart && !toEnd) {
1230 >                if (m.compare(lo, hi) > 0)
1231 >                    throw new IllegalArgumentException("fromKey > toKey");
1232              } else {
1233 <                toEnd = true;
1234 <                fromKey = key;
1233 >                if (!fromStart) // type check
1234 >                    m.compare(lo, lo);
1235 >                if (!toEnd)
1236 >                    m.compare(hi, hi);
1237              }
1235        }
1238  
1239 <        SubMap(boolean fromStart, K fromKey, boolean toEnd, K toKey) {
1239 >            this.m = m;
1240              this.fromStart = fromStart;
1241 <            this.fromKey= fromKey;
1241 >            this.lo = lo;
1242 >            this.loInclusive = loInclusive;
1243              this.toEnd = toEnd;
1244 <            this.toKey = toKey;
1244 >            this.hi = hi;
1245 >            this.hiInclusive = hiInclusive;
1246 >        }
1247 >
1248 >        // internal utilities
1249 >
1250 >        final boolean tooLow(Object key) {
1251 >            if (!fromStart) {
1252 >                int c = m.compare(key, lo);
1253 >                if (c < 0 || (c == 0 && !loInclusive))
1254 >                    return true;
1255 >            }
1256 >            return false;
1257 >        }
1258 >
1259 >        final boolean tooHigh(Object key) {
1260 >            if (!toEnd) {
1261 >                int c = m.compare(key, hi);
1262 >                if (c > 0 || (c == 0 && !hiInclusive))
1263 >                    return true;
1264 >            }
1265 >            return false;
1266 >        }
1267 >
1268 >        final boolean inRange(Object key) {
1269 >            return !tooLow(key) && !tooHigh(key);
1270 >        }
1271 >
1272 >        final boolean inClosedRange(Object key) {
1273 >            return (fromStart || m.compare(key, lo) >= 0)
1274 >                && (toEnd || m.compare(hi, key) >= 0);
1275 >        }
1276 >
1277 >        final boolean inRange(Object key, boolean inclusive) {
1278 >            return inclusive ? inRange(key) : inClosedRange(key);
1279 >        }
1280 >
1281 >        /*
1282 >         * Absolute versions of relation operations.
1283 >         * Subclasses map to these using like-named "sub"
1284 >         * versions that invert senses for descending maps
1285 >         */
1286 >
1287 >        final TreeMap.Entry<K,V> absLowest() {
1288 >            TreeMap.Entry<K,V> e =
1289 >                (fromStart ?  m.getFirstEntry() :
1290 >                 (loInclusive ? m.getCeilingEntry(lo) :
1291 >                                m.getHigherEntry(lo)));
1292 >            return (e == null || tooHigh(e.key)) ? null : e;
1293 >        }
1294 >
1295 >        final TreeMap.Entry<K,V> absHighest() {
1296 >            TreeMap.Entry<K,V> e =
1297 >                (toEnd ?  m.getLastEntry() :
1298 >                 (hiInclusive ?  m.getFloorEntry(hi) :
1299 >                                 m.getLowerEntry(hi)));
1300 >            return (e == null || tooLow(e.key)) ? null : e;
1301          }
1302  
1303 +        final TreeMap.Entry<K,V> absCeiling(K key) {
1304 +            if (tooLow(key))
1305 +                return absLowest();
1306 +            TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
1307 +            return (e == null || tooHigh(e.key)) ? null : e;
1308 +        }
1309 +
1310 +        final TreeMap.Entry<K,V> absHigher(K key) {
1311 +            if (tooLow(key))
1312 +                return absLowest();
1313 +            TreeMap.Entry<K,V> e = m.getHigherEntry(key);
1314 +            return (e == null || tooHigh(e.key)) ? null : e;
1315 +        }
1316 +
1317 +        final TreeMap.Entry<K,V> absFloor(K key) {
1318 +            if (tooHigh(key))
1319 +                return absHighest();
1320 +            TreeMap.Entry<K,V> e = m.getFloorEntry(key);
1321 +            return (e == null || tooLow(e.key)) ? null : e;
1322 +        }
1323 +
1324 +        final TreeMap.Entry<K,V> absLower(K key) {
1325 +            if (tooHigh(key))
1326 +                return absHighest();
1327 +            TreeMap.Entry<K,V> e = m.getLowerEntry(key);
1328 +            return (e == null || tooLow(e.key)) ? null : e;
1329 +        }
1330 +
1331 +        /** Returns the absolute high fence for ascending traversal */
1332 +        final TreeMap.Entry<K,V> absHighFence() {
1333 +            return (toEnd ? null : (hiInclusive ?
1334 +                                    m.getHigherEntry(hi) :
1335 +                                    m.getCeilingEntry(hi)));
1336 +        }
1337 +
1338 +        /** Return the absolute low fence for descending traversal  */
1339 +        final TreeMap.Entry<K,V> absLowFence() {
1340 +            return (fromStart ? null : (loInclusive ?
1341 +                                        m.getLowerEntry(lo) :
1342 +                                        m.getFloorEntry(lo)));
1343 +        }
1344 +
1345 +        // Abstract methods defined in ascending vs descending classes
1346 +        // These relay to the appropriate  absolute versions
1347 +
1348 +        abstract TreeMap.Entry<K,V> subLowest();
1349 +        abstract TreeMap.Entry<K,V> subHighest();
1350 +        abstract TreeMap.Entry<K,V> subCeiling(K key);
1351 +        abstract TreeMap.Entry<K,V> subHigher(K key);
1352 +        abstract TreeMap.Entry<K,V> subFloor(K key);
1353 +        abstract TreeMap.Entry<K,V> subLower(K key);
1354 +
1355 +        /** Returns ascending iterator from the perspective of this submap */
1356 +        abstract Iterator<K> keyIterator();
1357 +
1358 +        /** Returns descending iterator from the perspective of this submap */
1359 +        abstract Iterator<K> descendingKeyIterator();
1360 +
1361 +        // public methods
1362 +
1363          public boolean isEmpty() {
1364 <            return entrySet.isEmpty();
1364 >            return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1365          }
1366  
1367 <        public boolean containsKey(Object key) {
1368 <            return inRange((K) key) && TreeMap.this.containsKey(key);
1367 >        public int size() {
1368 >            return (fromStart && toEnd) ? m.size() : entrySet().size();
1369          }
1370  
1371 <        public V get(Object key) {
1372 <            if (!inRange((K) key))
1254 <                return null;
1255 <            return TreeMap.this.get(key);
1371 >        public final boolean containsKey(Object key) {
1372 >            return inRange(key) && m.containsKey(key);
1373          }
1374  
1375 <        public V put(K key, V value) {
1375 >        public final V put(K key, V value) {
1376              if (!inRange(key))
1377                  throw new IllegalArgumentException("key out of range");
1378 <            return TreeMap.this.put(key, value);
1378 >            return m.put(key, value);
1379          }
1380  
1381 <        public V remove(Object key) {
1382 <            if (!inRange((K) key))
1266 <                return null;
1267 <            return TreeMap.this.remove(key);
1381 >        public final V get(Object key) {
1382 >            return !inRange(key)? null :  m.get(key);
1383          }
1384  
1385 <        public Comparator<? super K> comparator() {
1386 <            return comparator;
1385 >        public final V remove(Object key) {
1386 >            return !inRange(key)? null  : m.remove(key);
1387          }
1388  
1389 <        public K firstKey() {
1390 <            TreeMap.Entry<K,V> e = fromStart ? getFirstEntry() : getCeilingEntry(fromKey);
1276 <            K first = key(e);
1277 <            if (!toEnd && compare(first, toKey) >= 0)
1278 <                throw(new NoSuchElementException());
1279 <            return first;
1280 <        }
1281 <
1282 <        public K lastKey() {
1283 <            TreeMap.Entry<K,V> e = toEnd ? getLastEntry() : getLowerEntry(toKey);
1284 <            K last = key(e);
1285 <            if (!fromStart && compare(last, fromKey) < 0)
1286 <                throw(new NoSuchElementException());
1287 <            return last;
1288 <        }
1289 <
1290 <        public Map.Entry<K,V> firstEntry() {
1291 <            TreeMap.Entry<K,V> e = fromStart ?
1292 <                getFirstEntry() : getCeilingEntry(fromKey);
1293 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1294 <                return null;
1295 <            return e;
1389 >        public final Map.Entry<K,V> ceilingEntry(K key) {
1390 >            return exportEntry(subCeiling(key));
1391          }
1392  
1393 <        public Map.Entry<K,V> lastEntry() {
1394 <            TreeMap.Entry<K,V> e = toEnd ?
1300 <                getLastEntry() : getLowerEntry(toKey);
1301 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1302 <                return null;
1303 <            return e;
1393 >        public final K ceilingKey(K key) {
1394 >            return keyOrNull(subCeiling(key));
1395          }
1396  
1397 <        public Map.Entry<K,V> pollFirstEntry() {
1398 <            TreeMap.Entry<K,V> e = fromStart ?
1308 <                getFirstEntry() : getCeilingEntry(fromKey);
1309 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1310 <                return null;
1311 <            Map.Entry result = new SnapshotEntry(e);
1312 <            deleteEntry(e);
1313 <            return result;
1397 >        public final Map.Entry<K,V> higherEntry(K key) {
1398 >            return exportEntry(subHigher(key));
1399          }
1400  
1401 <        public Map.Entry<K,V> pollLastEntry() {
1402 <            TreeMap.Entry<K,V> e = toEnd ?
1318 <                getLastEntry() : getLowerEntry(toKey);
1319 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1320 <                return null;
1321 <            Map.Entry result = new SnapshotEntry(e);
1322 <            deleteEntry(e);
1323 <            return result;
1401 >        public final K higherKey(K key) {
1402 >            return keyOrNull(subHigher(key));
1403          }
1404  
1405 <        private TreeMap.Entry<K,V> subceiling(K key) {
1406 <            TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1328 <                getCeilingEntry(fromKey) : getCeilingEntry(key);
1329 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1330 <                return null;
1331 <            return e;
1405 >        public final Map.Entry<K,V> floorEntry(K key) {
1406 >            return exportEntry(subFloor(key));
1407          }
1408  
1409 <        public Map.Entry<K,V> ceilingEntry(K key) {
1410 <            TreeMap.Entry<K,V> e = subceiling(key);
1336 <            return e == null? null : new SnapshotEntry(e);
1409 >        public final K floorKey(K key) {
1410 >            return keyOrNull(subFloor(key));
1411          }
1412  
1413 <        public K ceilingKey(K key) {
1414 <            TreeMap.Entry<K,V> e = subceiling(key);
1341 <            return e == null? null : e.key;
1413 >        public final Map.Entry<K,V> lowerEntry(K key) {
1414 >            return exportEntry(subLower(key));
1415          }
1416  
1417 +        public final K lowerKey(K key) {
1418 +            return keyOrNull(subLower(key));
1419 +        }
1420  
1421 <        private TreeMap.Entry<K,V> subhigher(K key) {
1422 <            TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1347 <                getCeilingEntry(fromKey) : getHigherEntry(key);
1348 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1349 <                return null;
1350 <            return e;
1421 >        public final K firstKey() {
1422 >            return key(subLowest());
1423          }
1424  
1425 <        public Map.Entry<K,V> higherEntry(K key) {
1426 <            TreeMap.Entry<K,V> e = subhigher(key);
1355 <            return e == null? null : new SnapshotEntry(e);
1425 >        public final K lastKey() {
1426 >            return key(subHighest());
1427          }
1428  
1429 <        public K higherKey(K key) {
1430 <            TreeMap.Entry<K,V> e = subhigher(key);
1360 <            return e == null? null : e.key;
1429 >        public final Map.Entry<K,V> firstEntry() {
1430 >            return exportEntry(subLowest());
1431          }
1432  
1433 <        private TreeMap.Entry<K,V> subfloor(K key) {
1434 <            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1365 <                getLowerEntry(toKey) : getFloorEntry(key);
1366 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1367 <                return null;
1368 <            return e;
1433 >        public final Map.Entry<K,V> lastEntry() {
1434 >            return exportEntry(subHighest());
1435          }
1436  
1437 <        public Map.Entry<K,V> floorEntry(K key) {
1438 <            TreeMap.Entry<K,V> e = subfloor(key);
1439 <            return e == null? null : new SnapshotEntry(e);
1437 >        public final Map.Entry<K,V> pollFirstEntry() {
1438 >            TreeMap.Entry<K,V> e = subLowest();
1439 >            Map.Entry<K,V> result = exportEntry(e);
1440 >            if (e != null)
1441 >                m.deleteEntry(e);
1442 >            return result;
1443          }
1444  
1445 <        public K floorKey(K key) {
1446 <            TreeMap.Entry<K,V> e = subfloor(key);
1447 <            return e == null? null : e.key;
1445 >        public final Map.Entry<K,V> pollLastEntry() {
1446 >            TreeMap.Entry<K,V> e = subHighest();
1447 >            Map.Entry<K,V> result = exportEntry(e);
1448 >            if (e != null)
1449 >                m.deleteEntry(e);
1450 >            return result;
1451          }
1452  
1453 <        private TreeMap.Entry<K,V> sublower(K key) {
1454 <            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1455 <                getLowerEntry(toKey) :  getLowerEntry(key);
1456 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1457 <                return null;
1458 <            return e;
1453 >        // Views
1454 >        transient NavigableMap<K,V> descendingMapView = null;
1455 >        transient EntrySetView entrySetView = null;
1456 >        transient KeySet<K> navigableKeySetView = null;
1457 >
1458 >        public final NavigableSet<K> navigableKeySet() {
1459 >            KeySet<K> nksv = navigableKeySetView;
1460 >            return (nksv != null) ? nksv :
1461 >                (navigableKeySetView = new TreeMap.KeySet(this));
1462          }
1463  
1464 <        public Map.Entry<K,V> lowerEntry(K key) {
1465 <            TreeMap.Entry<K,V> e = sublower(key);
1391 <            return e == null? null : new SnapshotEntry(e);
1464 >        public final Set<K> keySet() {
1465 >            return navigableKeySet();
1466          }
1467  
1468 <        public K lowerKey(K key) {
1469 <            TreeMap.Entry<K,V> e = sublower(key);
1396 <            return e == null? null : e.key;
1468 >        public NavigableSet<K> descendingKeySet() {
1469 >            return descendingMap().navigableKeySet();
1470          }
1471  
1472 <        private transient Set<Map.Entry<K,V>> entrySet = new EntrySetView();
1472 >        public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1473 >            return subMap(fromKey, true, toKey, false);
1474 >        }
1475  
1476 <        public Set<Map.Entry<K,V>> entrySet() {
1477 <            return entrySet;
1476 >        public final SortedMap<K,V> headMap(K toKey) {
1477 >            return headMap(toKey, false);
1478          }
1479  
1480 <        private class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1480 >        public final SortedMap<K,V> tailMap(K fromKey) {
1481 >            return tailMap(fromKey, true);
1482 >        }
1483 >
1484 >        // View classes
1485 >
1486 >        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1487              private transient int size = -1, sizeModCount;
1488  
1489              public int size() {
1490 <                if (size == -1 || sizeModCount != TreeMap.this.modCount) {
1491 <                    size = 0;  sizeModCount = TreeMap.this.modCount;
1490 >                if (fromStart && toEnd)
1491 >                    return m.size();
1492 >                if (size == -1 || sizeModCount != m.modCount) {
1493 >                    sizeModCount = m.modCount;
1494 >                    size = 0;
1495                      Iterator i = iterator();
1496                      while (i.hasNext()) {
1497                          size++;
# Line 1418 | Line 1502 | public class TreeMap<K,V>
1502              }
1503  
1504              public boolean isEmpty() {
1505 <                return !iterator().hasNext();
1505 >                TreeMap.Entry<K,V> n = absLowest();
1506 >                return n == null || tooHigh(n.key);
1507              }
1508  
1509              public boolean contains(Object o) {
# Line 1428 | Line 1513 | public class TreeMap<K,V>
1513                  K key = entry.getKey();
1514                  if (!inRange(key))
1515                      return false;
1516 <                TreeMap.Entry node = getEntry(key);
1516 >                TreeMap.Entry node = m.getEntry(key);
1517                  return node != null &&
1518 <                       valEquals(node.getValue(), entry.getValue());
1518 >                    valEquals(node.getValue(), entry.getValue());
1519              }
1520  
1521              public boolean remove(Object o) {
# Line 1440 | Line 1525 | public class TreeMap<K,V>
1525                  K key = entry.getKey();
1526                  if (!inRange(key))
1527                      return false;
1528 <                TreeMap.Entry<K,V> node = getEntry(key);
1528 >                TreeMap.Entry<K,V> node = m.getEntry(key);
1529                  if (node!=null && valEquals(node.getValue(),entry.getValue())){
1530 <                    deleteEntry(node);
1530 >                    m.deleteEntry(node);
1531                      return true;
1532                  }
1533                  return false;
1534              }
1450
1451            public Iterator<Map.Entry<K,V>> iterator() {
1452                return new SubMapEntryIterator(
1453                    (fromStart ? getFirstEntry() : getCeilingEntry(fromKey)),
1454                    (toEnd     ? null            : getCeilingEntry(toKey)));
1455            }
1535          }
1536  
1537 <        private transient Set<Map.Entry<K,V>> descendingEntrySetView = null;
1538 <        private transient Set<K> descendingKeySetView = null;
1539 <
1540 <        public Set<Map.Entry<K,V>> descendingEntrySet() {
1541 <            Set<Map.Entry<K,V>> es = descendingEntrySetView;
1542 <            return (es != null) ? es : (descendingEntrySetView = new DescendingEntrySetView());
1543 <        }
1537 >        /**
1538 >         * Iterators for SubMaps
1539 >         */
1540 >        abstract class SubMapIterator<T> implements Iterator<T> {
1541 >            TreeMap.Entry<K,V> lastReturned;
1542 >            TreeMap.Entry<K,V> next;
1543 >            final K fenceKey;
1544 >            int expectedModCount;
1545  
1546 <        public Set<K> descendingKeySet() {
1547 <            Set<K> ks = descendingKeySetView;
1548 <            return (ks != null) ? ks : (descendingKeySetView = new DescendingKeySetView());
1549 <        }
1546 >            SubMapIterator(TreeMap.Entry<K,V> first,
1547 >                           TreeMap.Entry<K,V> fence) {
1548 >                expectedModCount = m.modCount;
1549 >                lastReturned = null;
1550 >                next = first;
1551 >                fenceKey = fence == null ? null : fence.key;
1552 >            }
1553  
1554 <        private class DescendingEntrySetView extends EntrySetView {
1555 <            public Iterator<Map.Entry<K,V>> iterator() {
1473 <                return new DescendingSubMapEntryIterator
1474 <                    ((toEnd     ? getLastEntry()  : getLowerEntry(toKey)),
1475 <                     (fromStart ? null            : getLowerEntry(fromKey)));
1554 >            public final boolean hasNext() {
1555 >                return next != null && next.key != fenceKey;
1556              }
1477        }
1557  
1558 <        private class DescendingKeySetView extends AbstractSet<K> {
1559 <            public Iterator<K> iterator() {
1560 <                return new Iterator<K>() {
1561 <                    private Iterator<Entry<K,V>> i = descendingEntrySet().iterator();
1562 <                    
1563 <                    public boolean hasNext() { return i.hasNext(); }
1564 <                    public K next() { return i.next().getKey(); }
1565 <                    public void remove() { i.remove(); }
1487 <                };
1558 >            final TreeMap.Entry<K,V> nextEntry() {
1559 >                TreeMap.Entry<K,V> e = lastReturned = next;
1560 >                if (e == null || e.key == fenceKey)
1561 >                    throw new NoSuchElementException();
1562 >                if (m.modCount != expectedModCount)
1563 >                    throw new ConcurrentModificationException();
1564 >                next = successor(e);
1565 >                return e;
1566              }
1567 <            
1568 <            public int size() {
1569 <                return SubMap.this.size();
1567 >
1568 >            final TreeMap.Entry<K,V> prevEntry() {
1569 >                TreeMap.Entry<K,V> e = lastReturned = next;
1570 >                if (e == null || e.key == fenceKey)
1571 >                    throw new NoSuchElementException();
1572 >                if (m.modCount != expectedModCount)
1573 >                    throw new ConcurrentModificationException();
1574 >                next = predecessor(e);
1575 >                return e;
1576              }
1577 <            
1578 <            public boolean contains(Object k) {
1579 <                return SubMap.this.containsKey(k);
1577 >
1578 >            public void remove() {
1579 >                if (lastReturned == null)
1580 >                    throw new IllegalStateException();
1581 >                if (m.modCount != expectedModCount)
1582 >                    throw new ConcurrentModificationException();
1583 >                if (lastReturned.left != null && lastReturned.right != null)
1584 >                    next = lastReturned;
1585 >                m.deleteEntry(lastReturned);
1586 >                expectedModCount++;
1587 >                lastReturned = null;
1588              }
1589          }
1590  
1591 <
1592 <        public NavigableMap<K,V> subMap(K fromKey, K toKey) {
1593 <            if (!inRange2(fromKey))
1594 <                throw new IllegalArgumentException("fromKey out of range");
1595 <            if (!inRange2(toKey))
1596 <                throw new IllegalArgumentException("toKey out of range");
1597 <            return new SubMap(fromKey, toKey);
1591 >        final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1592 >            SubMapEntryIterator(TreeMap.Entry<K,V> first,
1593 >                                TreeMap.Entry<K,V> fence) {
1594 >                super(first, fence);
1595 >            }
1596 >            public Map.Entry<K,V> next() {
1597 >                return nextEntry();
1598 >            }
1599          }
1600  
1601 <        public NavigableMap<K,V> headMap(K toKey) {
1602 <            if (!inRange2(toKey))
1603 <                throw new IllegalArgumentException("toKey out of range");
1604 <            return new SubMap(fromStart, fromKey, false, toKey);
1601 >        final class SubMapKeyIterator extends SubMapIterator<K> {
1602 >            SubMapKeyIterator(TreeMap.Entry<K,V> first,
1603 >                              TreeMap.Entry<K,V> fence) {
1604 >                super(first, fence);
1605 >            }
1606 >            public K next() {
1607 >                return nextEntry().key;
1608 >            }
1609          }
1610  
1611 <        public NavigableMap<K,V> tailMap(K fromKey) {
1612 <            if (!inRange2(fromKey))
1613 <                throw new IllegalArgumentException("fromKey out of range");
1614 <            return new SubMap(false, fromKey, toEnd, toKey);
1615 <        }
1611 >        final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1612 >            DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
1613 >                                          TreeMap.Entry<K,V> fence) {
1614 >                super(last, fence);
1615 >            }
1616  
1617 <        private boolean inRange(K key) {
1618 <            return (fromStart || compare(key, fromKey) >= 0) &&
1619 <                   (toEnd     || compare(key, toKey)   <  0);
1617 >            public Map.Entry<K,V> next() {
1618 >                return prevEntry();
1619 >            }
1620          }
1621  
1622 <        // This form allows the high endpoint (as well as all legit keys)
1623 <        private boolean inRange2(K key) {
1624 <            return (fromStart || compare(key, fromKey) >= 0) &&
1625 <                   (toEnd     || compare(key, toKey)   <= 0);
1622 >        final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
1623 >            DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
1624 >                                        TreeMap.Entry<K,V> fence) {
1625 >                super(last, fence);
1626 >            }
1627 >            public K next() {
1628 >                return prevEntry().key;
1629 >            }
1630          }
1631      }
1632  
1633 <    /**
1634 <     * TreeMap Iterator.
1534 <     */
1535 <    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1536 <        int expectedModCount = TreeMap.this.modCount;
1537 <        Entry<K,V> lastReturned = null;
1538 <        Entry<K,V> next;
1633 >    static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1634 >        private static final long serialVersionUID = 912986545866124060L;
1635  
1636 <        PrivateEntryIterator(Entry<K,V> first) {
1637 <            next = first;
1636 >        AscendingSubMap(TreeMap<K,V> m,
1637 >                        boolean fromStart, K lo, boolean loInclusive,
1638 >                        boolean toEnd, K hi, boolean hiInclusive) {
1639 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1640          }
1641  
1642 <        public boolean hasNext() {
1643 <            return next != null;
1642 >        public Comparator<? super K> comparator() {
1643 >            return m.comparator();
1644          }
1645  
1646 <        Entry<K,V> nextEntry() {
1647 <            if (next == null)
1648 <                throw new NoSuchElementException();
1649 <            if (modCount != expectedModCount)
1650 <                throw new ConcurrentModificationException();
1651 <            lastReturned = next;
1652 <            next = successor(next);
1653 <            return lastReturned;
1646 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1647 >                                        K toKey, boolean toInclusive) {
1648 >            if (!inRange(fromKey, fromInclusive))
1649 >                throw new IllegalArgumentException("fromKey out of range");
1650 >            if (!inRange(toKey, toInclusive))
1651 >                throw new IllegalArgumentException("toKey out of range");
1652 >            return new AscendingSubMap(m,
1653 >                                       false, fromKey, fromInclusive,
1654 >                                       false, toKey,   toInclusive);
1655          }
1656  
1657 <        public void remove() {
1658 <            if (lastReturned == null)
1659 <                throw new IllegalStateException();
1660 <            if (modCount != expectedModCount)
1661 <                throw new ConcurrentModificationException();
1662 <            if (lastReturned.left != null && lastReturned.right != null)
1564 <                next = lastReturned;
1565 <            deleteEntry(lastReturned);
1566 <            expectedModCount++;
1567 <            lastReturned = null;
1657 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1658 >            if (!inClosedRange(toKey))
1659 >                throw new IllegalArgumentException("toKey out of range");
1660 >            return new AscendingSubMap(m,
1661 >                                       fromStart, lo,    loInclusive,
1662 >                                       false,     toKey, inclusive);
1663          }
1569    }
1664  
1665 <    class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1666 <        EntryIterator(Entry<K,V> first) {
1667 <            super(first);
1665 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1666 >            if (!inRange(fromKey, inclusive))
1667 >                throw new IllegalArgumentException("fromKey out of range");
1668 >            return new AscendingSubMap(m,
1669 >                                       false, fromKey, inclusive,
1670 >                                       toEnd, hi,      hiInclusive);
1671          }
1672  
1673 <        public Map.Entry<K,V> next() {
1674 <            return nextEntry();
1673 >        public NavigableMap<K,V> descendingMap() {
1674 >            NavigableMap<K,V> mv = descendingMapView;
1675 >            return (mv != null) ? mv :
1676 >                (descendingMapView =
1677 >                 new DescendingSubMap(m,
1678 >                                      fromStart, lo, loInclusive,
1679 >                                      toEnd,     hi, hiInclusive));
1680          }
1579    }
1681  
1682 <    class KeyIterator extends PrivateEntryIterator<K> {
1683 <        KeyIterator(Entry<K,V> first) {
1583 <            super(first);
1682 >        Iterator<K> keyIterator() {
1683 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1684          }
1585        public K next() {
1586            return nextEntry().key;
1587        }
1588    }
1685  
1686 <    class ValueIterator extends PrivateEntryIterator<V> {
1687 <        ValueIterator(Entry<K,V> first) {
1592 <            super(first);
1593 <        }
1594 <        public V next() {
1595 <            return nextEntry().value;
1686 >        Iterator<K> descendingKeyIterator() {
1687 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1688          }
1597    }
1598
1599    class SubMapEntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1600        private final K firstExcludedKey;
1689  
1690 <        SubMapEntryIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1691 <            super(first);
1692 <            firstExcludedKey = (firstExcluded == null
1693 <                                ? null
1606 <                                : firstExcluded.key);
1690 >        final class AscendingEntrySetView extends EntrySetView {
1691 >            public Iterator<Map.Entry<K,V>> iterator() {
1692 >                return new SubMapEntryIterator(absLowest(), absHighFence());
1693 >            }
1694          }
1695  
1696 <        public boolean hasNext() {
1697 <            return next != null && next.key != firstExcludedKey;
1696 >        public Set<Map.Entry<K,V>> entrySet() {
1697 >            EntrySetView es = entrySetView;
1698 >            return (es != null) ? es : new AscendingEntrySetView();
1699          }
1700  
1701 <        public Map.Entry<K,V> next() {
1702 <            if (next == null || next.key == firstExcludedKey)
1703 <                throw new NoSuchElementException();
1704 <            return nextEntry();
1705 <        }
1701 >        TreeMap.Entry<K,V> subLowest()       { return absLowest(); }
1702 >        TreeMap.Entry<K,V> subHighest()      { return absHighest(); }
1703 >        TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); }
1704 >        TreeMap.Entry<K,V> subHigher(K key)  { return absHigher(key); }
1705 >        TreeMap.Entry<K,V> subFloor(K key)   { return absFloor(key); }
1706 >        TreeMap.Entry<K,V> subLower(K key)   { return absLower(key); }
1707      }
1708  
1709 <
1710 <    /**
1711 <     * Base for Descending Iterators.
1712 <     */
1713 <    abstract class DescendingPrivateEntryIterator<T> extends PrivateEntryIterator<T> {
1714 <        DescendingPrivateEntryIterator(Entry<K,V> first) {
1626 <            super(first);
1709 >    static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
1710 >        private static final long serialVersionUID = 912986545866120460L;
1711 >        DescendingSubMap(TreeMap<K,V> m,
1712 >                        boolean fromStart, K lo, boolean loInclusive,
1713 >                        boolean toEnd, K hi, boolean hiInclusive) {
1714 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1715          }
1716  
1717 <        Entry<K,V> nextEntry() {
1718 <            if (next == null)
1631 <                throw new NoSuchElementException();
1632 <            if (modCount != expectedModCount)
1633 <                throw new ConcurrentModificationException();
1634 <            lastReturned = next;
1635 <            next = predecessor(next);
1636 <            return lastReturned;
1637 <        }
1638 <    }
1717 >        private final Comparator<? super K> reverseComparator =
1718 >            Collections.reverseOrder(m.comparator);
1719  
1720 <    class DescendingEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1721 <        DescendingEntryIterator(Entry<K,V> first) {
1642 <            super(first);
1720 >        public Comparator<? super K> comparator() {
1721 >            return reverseComparator;
1722          }
1723 <        public Map.Entry<K,V> next() {
1724 <            return nextEntry();
1723 >
1724 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1725 >                                        K toKey, boolean toInclusive) {
1726 >            if (!inRange(fromKey, fromInclusive))
1727 >                throw new IllegalArgumentException("fromKey out of range");
1728 >            if (!inRange(toKey, toInclusive))
1729 >                throw new IllegalArgumentException("toKey out of range");
1730 >            return new DescendingSubMap(m,
1731 >                                        false, toKey,   toInclusive,
1732 >                                        false, fromKey, fromInclusive);
1733          }
1647    }
1734  
1735 <    class DescendingKeyIterator extends DescendingPrivateEntryIterator<K> {
1736 <        DescendingKeyIterator(Entry<K,V> first) {
1737 <            super(first);
1735 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1736 >            if (!inRange(toKey, inclusive))
1737 >                throw new IllegalArgumentException("toKey out of range");
1738 >            return new DescendingSubMap(m,
1739 >                                        false, toKey, inclusive,
1740 >                                        toEnd, hi,    hiInclusive);
1741          }
1742 <        public K next() {
1743 <            return nextEntry().key;
1742 >
1743 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1744 >            if (!inRange(fromKey, inclusive))
1745 >                throw new IllegalArgumentException("fromKey out of range");
1746 >            return new DescendingSubMap(m,
1747 >                                        fromStart, lo, loInclusive,
1748 >                                        false, fromKey, inclusive);
1749          }
1656    }
1750  
1751 +        public NavigableMap<K,V> descendingMap() {
1752 +            NavigableMap<K,V> mv = descendingMapView;
1753 +            return (mv != null) ? mv :
1754 +                (descendingMapView =
1755 +                 new AscendingSubMap(m,
1756 +                                     fromStart, lo, loInclusive,
1757 +                                     toEnd,     hi, hiInclusive));
1758 +        }
1759  
1760 <    class DescendingSubMapEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1761 <        private final K lastExcludedKey;
1760 >        Iterator<K> keyIterator() {
1761 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1762 >        }
1763  
1764 <        DescendingSubMapEntryIterator(Entry<K,V> last, Entry<K,V> lastExcluded) {
1765 <            super(last);
1664 <            lastExcludedKey = (lastExcluded == null
1665 <                                ? null
1666 <                                : lastExcluded.key);
1764 >        Iterator<K> descendingKeyIterator() {
1765 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1766          }
1767  
1768 <        public boolean hasNext() {
1769 <            return next != null && next.key != lastExcludedKey;
1768 >        final class DescendingEntrySetView extends EntrySetView {
1769 >            public Iterator<Map.Entry<K,V>> iterator() {
1770 >                return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
1771 >            }
1772          }
1773  
1774 <        public Map.Entry<K,V> next() {
1775 <            if (next == null || next.key == lastExcludedKey)
1776 <                throw new NoSuchElementException();
1676 <            return nextEntry();
1774 >        public Set<Map.Entry<K,V>> entrySet() {
1775 >            EntrySetView es = entrySetView;
1776 >            return (es != null) ? es : new DescendingEntrySetView();
1777          }
1778  
1779 +        TreeMap.Entry<K,V> subLowest()       { return absHighest(); }
1780 +        TreeMap.Entry<K,V> subHighest()      { return absLowest(); }
1781 +        TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
1782 +        TreeMap.Entry<K,V> subHigher(K key)  { return absLower(key); }
1783 +        TreeMap.Entry<K,V> subFloor(K key)   { return absCeiling(key); }
1784 +        TreeMap.Entry<K,V> subLower(K key)   { return absHigher(key); }
1785      }
1786  
1681
1787      /**
1788 <     * Compares two keys using the correct comparison method for this TreeMap.
1788 >     * This class exists solely for the sake of serialization
1789 >     * compatibility with previous releases of TreeMap that did not
1790 >     * support NavigableMap.  It translates an old-version SubMap into
1791 >     * a new-version AscendingSubMap. This class is never otherwise
1792 >     * used.
1793       */
1794 <    private int compare(K k1, K k2) {
1795 <        return (comparator==null ? ((Comparable</*-*/K>)k1).compareTo(k2)
1796 <                                 : comparator.compare((K)k1, (K)k2));
1794 >    private class SubMap extends AbstractMap<K,V>
1795 >        implements SortedMap<K,V>, java.io.Serializable {
1796 >        private static final long serialVersionUID = -6520786458950516097L;
1797 >        private boolean fromStart = false, toEnd = false;
1798 >        private K fromKey, toKey;
1799 >        private Object readResolve() {
1800 >            return new AscendingSubMap(TreeMap.this,
1801 >                                       fromStart, fromKey, true,
1802 >                                       toEnd, toKey, false);
1803 >        }
1804 >        public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
1805 >        public K lastKey() { throw new InternalError(); }
1806 >        public K firstKey() { throw new InternalError(); }
1807 >        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
1808 >        public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
1809 >        public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
1810 >        public Comparator<? super K> comparator() { throw new InternalError(); }
1811      }
1812  
1813 <    /**
1814 <     * Test two values  for equality.  Differs from o1.equals(o2) only in
1692 <     * that it copes with <tt>null</tt> o1 properly.
1693 <     */
1694 <    private static boolean valEquals(Object o1, Object o2) {
1695 <        return (o1==null ? o2==null : o1.equals(o2));
1696 <    }
1813 >
1814 >    // Red-black mechanics
1815  
1816      private static final boolean RED   = false;
1817      private static final boolean BLACK = true;
# Line 1703 | Line 1821 | public class TreeMap<K,V>
1821       * user (see Map.Entry).
1822       */
1823  
1824 <    static class Entry<K,V> implements Map.Entry<K,V> {
1824 >    static final class Entry<K,V> implements Map.Entry<K,V> {
1825          K key;
1826          V value;
1827          Entry<K,V> left = null;
# Line 1724 | Line 1842 | public class TreeMap<K,V>
1842          /**
1843           * Returns the key.
1844           *
1845 <         * @return the key.
1845 >         * @return the key
1846           */
1847          public K getKey() {
1848              return key;
# Line 1733 | Line 1851 | public class TreeMap<K,V>
1851          /**
1852           * Returns the value associated with the key.
1853           *
1854 <         * @return the value associated with the key.
1854 >         * @return the value associated with the key
1855           */
1856          public V getValue() {
1857              return value;
# Line 1744 | Line 1862 | public class TreeMap<K,V>
1862           * value.
1863           *
1864           * @return the value associated with the key before this method was
1865 <         *           called.
1865 >         *         called
1866           */
1867          public V setValue(V value) {
1868              V oldValue = this.value;
# Line 1775 | Line 1893 | public class TreeMap<K,V>
1893       * Returns the first Entry in the TreeMap (according to the TreeMap's
1894       * key-sort function).  Returns null if the TreeMap is empty.
1895       */
1896 <    private Entry<K,V> getFirstEntry() {
1896 >    final Entry<K,V> getFirstEntry() {
1897          Entry<K,V> p = root;
1898          if (p != null)
1899              while (p.left != null)
# Line 1787 | Line 1905 | public class TreeMap<K,V>
1905       * Returns the last Entry in the TreeMap (according to the TreeMap's
1906       * key-sort function).  Returns null if the TreeMap is empty.
1907       */
1908 <    private Entry<K,V> getLastEntry() {
1908 >    final Entry<K,V> getLastEntry() {
1909          Entry<K,V> p = root;
1910          if (p != null)
1911              while (p.right != null)
# Line 1798 | Line 1916 | public class TreeMap<K,V>
1916      /**
1917       * Returns the successor of the specified Entry, or null if no such.
1918       */
1919 <    private Entry<K,V> successor(Entry<K,V> t) {
1919 >    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
1920          if (t == null)
1921              return null;
1922          else if (t.right != null) {
# Line 1820 | Line 1938 | public class TreeMap<K,V>
1938      /**
1939       * Returns the predecessor of the specified Entry, or null if no such.
1940       */
1941 <    private Entry<K,V> predecessor(Entry<K,V> t) {
1941 >    static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {
1942          if (t == null)
1943              return null;
1944          else if (t.left != null) {
# Line 1870 | Line 1988 | public class TreeMap<K,V>
1988          return (p == null) ? null: p.right;
1989      }
1990  
1991 <    /** From CLR **/
1991 >    /** From CLR */
1992      private void rotateLeft(Entry<K,V> p) {
1993 <        Entry<K,V> r = p.right;
1994 <        p.right = r.left;
1995 <        if (r.left != null)
1996 <            r.left.parent = p;
1997 <        r.parent = p.parent;
1998 <        if (p.parent == null)
1999 <            root = r;
2000 <        else if (p.parent.left == p)
2001 <            p.parent.left = r;
2002 <        else
2003 <            p.parent.right = r;
2004 <        r.left = p;
2005 <        p.parent = r;
1993 >        if (p != null) {
1994 >            Entry<K,V> r = p.right;
1995 >            p.right = r.left;
1996 >            if (r.left != null)
1997 >                r.left.parent = p;
1998 >            r.parent = p.parent;
1999 >            if (p.parent == null)
2000 >                root = r;
2001 >            else if (p.parent.left == p)
2002 >                p.parent.left = r;
2003 >            else
2004 >                p.parent.right = r;
2005 >            r.left = p;
2006 >            p.parent = r;
2007 >        }
2008      }
2009  
2010 <    /** From CLR **/
2010 >    /** From CLR */
2011      private void rotateRight(Entry<K,V> p) {
2012 <        Entry<K,V> l = p.left;
2013 <        p.left = l.right;
2014 <        if (l.right != null) l.right.parent = p;
2015 <        l.parent = p.parent;
2016 <        if (p.parent == null)
2017 <            root = l;
2018 <        else if (p.parent.right == p)
2019 <            p.parent.right = l;
2020 <        else p.parent.left = l;
2021 <        l.right = p;
2022 <        p.parent = l;
2012 >        if (p != null) {
2013 >            Entry<K,V> l = p.left;
2014 >            p.left = l.right;
2015 >            if (l.right != null) l.right.parent = p;
2016 >            l.parent = p.parent;
2017 >            if (p.parent == null)
2018 >                root = l;
2019 >            else if (p.parent.right == p)
2020 >                p.parent.right = l;
2021 >            else p.parent.left = l;
2022 >            l.right = p;
2023 >            p.parent = l;
2024 >        }
2025      }
2026  
2027 <
1906 <    /** From CLR **/
2027 >    /** From CLR */
2028      private void fixAfterInsertion(Entry<K,V> x) {
2029          x.color = RED;
2030  
# Line 1922 | Line 2043 | public class TreeMap<K,V>
2043                      }
2044                      setColor(parentOf(x), BLACK);
2045                      setColor(parentOf(parentOf(x)), RED);
2046 <                    if (parentOf(parentOf(x)) != null)
1926 <                        rotateRight(parentOf(parentOf(x)));
2046 >                    rotateRight(parentOf(parentOf(x)));
2047                  }
2048              } else {
2049                  Entry<K,V> y = leftOf(parentOf(parentOf(x)));
# Line 1937 | Line 2057 | public class TreeMap<K,V>
2057                          x = parentOf(x);
2058                          rotateRight(x);
2059                      }
2060 <                    setColor(parentOf(x),  BLACK);
2060 >                    setColor(parentOf(x), BLACK);
2061                      setColor(parentOf(parentOf(x)), RED);
2062 <                    if (parentOf(parentOf(x)) != null)
1943 <                        rotateLeft(parentOf(parentOf(x)));
2062 >                    rotateLeft(parentOf(parentOf(x)));
2063                  }
2064              }
2065          }
# Line 1950 | Line 2069 | public class TreeMap<K,V>
2069      /**
2070       * Delete node p, and then rebalance the tree.
2071       */
1953
2072      private void deleteEntry(Entry<K,V> p) {
2073 <        decrementSize();
2073 >        modCount++;
2074 >        size--;
2075  
2076          // If strictly internal, copy successor's element to p and then make p
2077          // point to successor.
# Line 1998 | Line 2117 | public class TreeMap<K,V>
2117          }
2118      }
2119  
2120 <    /** From CLR **/
2120 >    /** From CLR */
2121      private void fixAfterDeletion(Entry<K,V> x) {
2122          while (x != root && colorOf(x) == BLACK) {
2123              if (x == leftOf(parentOf(x))) {
# Line 2013 | Line 2132 | public class TreeMap<K,V>
2132  
2133                  if (colorOf(leftOf(sib))  == BLACK &&
2134                      colorOf(rightOf(sib)) == BLACK) {
2135 <                    setColor(sib,  RED);
2135 >                    setColor(sib, RED);
2136                      x = parentOf(x);
2137                  } else {
2138                      if (colorOf(rightOf(sib)) == BLACK) {
# Line 2040 | Line 2159 | public class TreeMap<K,V>
2159  
2160                  if (colorOf(rightOf(sib)) == BLACK &&
2161                      colorOf(leftOf(sib)) == BLACK) {
2162 <                    setColor(sib,  RED);
2162 >                    setColor(sib, RED);
2163                      x = parentOf(x);
2164                  } else {
2165                      if (colorOf(leftOf(sib)) == BLACK) {
# Line 2091 | Line 2210 | public class TreeMap<K,V>
2210          }
2211      }
2212  
2094
2095
2213      /**
2214       * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e.,
2215       * deserialize it).
# Line 2108 | Line 2225 | public class TreeMap<K,V>
2225          buildFromSorted(size, null, s, null);
2226      }
2227  
2228 <    /** Intended to be called only from TreeSet.readObject **/
2228 >    /** Intended to be called only from TreeSet.readObject */
2229      void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2230          throws java.io.IOException, ClassNotFoundException {
2231          buildFromSorted(size, null, s, defaultVal);
2232      }
2233  
2234 <    /** Intended to be called only from TreeSet.addAll **/
2235 <    void addAllForTreeSet(SortedSet<Map.Entry<K,V>> set, V defaultVal) {
2234 >    /** Intended to be called only from TreeSet.addAll */
2235 >    void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2236          try {
2237              buildFromSorted(set.size(), set.iterator(), null, defaultVal);
2238          } catch (java.io.IOException cannotHappen) {
# Line 2140 | Line 2257 | public class TreeMap<K,V>
2257       * to calling this method.
2258       *
2259       * @param size the number of keys (or key-value pairs) to be read from
2260 <     *        the iterator or stream.
2260 >     *        the iterator or stream
2261       * @param it If non-null, new entries are created from entries
2262       *        or keys read from this iterator.
2263       * @param str If non-null, new entries are created from keys and
# Line 2154 | Line 2271 | public class TreeMap<K,V>
2271       * @throws ClassNotFoundException propagated from readObject.
2272       *         This cannot occur if str is null.
2273       */
2274 <    private
2275 <    void buildFromSorted(int size, Iterator it,
2276 <                         java.io.ObjectInputStream str,
2160 <                         V defaultVal)
2274 >    private void buildFromSorted(int size, Iterator it,
2275 >                                 java.io.ObjectInputStream str,
2276 >                                 V defaultVal)
2277          throws  java.io.IOException, ClassNotFoundException {
2278          this.size = size;
2279 <        root =
2280 <            buildFromSorted(0, 0, size-1, computeRedLevel(size),
2165 <                            it, str, defaultVal);
2279 >        root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
2280 >                               it, str, defaultVal);
2281      }
2282  
2283      /**
2284       * Recursive "helper method" that does the real work of the
2285 <     * of the previous method.  Identically named parameters have
2285 >     * previous method.  Identically named parameters have
2286       * identical definitions.  Additional parameters are documented below.
2287       * It is assumed that the comparator and size fields of the TreeMap are
2288       * already set prior to calling this method.  (It ignores both fields.)
# Line 2175 | Line 2290 | public class TreeMap<K,V>
2290       * @param level the current level of tree. Initial call should be 0.
2291       * @param lo the first element index of this subtree. Initial should be 0.
2292       * @param hi the last element index of this subtree.  Initial should be
2293 <     *              size-1.
2293 >     *        size-1.
2294       * @param redLevel the level at which nodes should be red.
2295       *        Must be equal to computeRedLevel for tree of this size.
2296       */
# Line 2259 | Line 2374 | public class TreeMap<K,V>
2374              level++;
2375          return level;
2376      }
2262
2263
2264    /**
2265     * Entry holding a snapshot of a key-value pair
2266     */
2267    static class SnapshotEntry<K,V> implements Map.Entry<K,V> {
2268        final K key;
2269        final V value;
2270
2271        public SnapshotEntry(Entry<K,V> e) {
2272            this.key   = e.getKey();
2273            this.value = e.getValue();
2274        }
2275
2276        public K getKey() {
2277            return key;
2278        }
2279
2280        public V getValue() {
2281            return value;
2282        }
2283
2284        /**
2285         * Always fails, throwing <tt>UnsupportedOperationException</tt>.
2286         * @throws UnsupportedOperationException always.
2287         */
2288        public V setValue(V value) {
2289            throw new UnsupportedOperationException();
2290        }
2291
2292        public boolean equals(Object o) {
2293            if (!(o instanceof Map.Entry))
2294                return false;
2295            Map.Entry e = (Map.Entry)o;
2296            return eq(key, e.getKey()) && eq(value, e.getValue());
2297        }
2298
2299        public int hashCode() {
2300            return ((key   == null)   ? 0 :   key.hashCode()) ^
2301                   ((value == null)   ? 0 : value.hashCode());
2302        }
2303
2304        public String toString() {
2305            return key + "=" + value;
2306        }
2307
2308        private static boolean eq(Object o1, Object o2) {
2309            return (o1 == null ? o2 == null : o1.equals(o2));
2310        }
2311    }
2312
2377   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines