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.33 by dl, Sat Apr 22 23:02:25 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)));
228 >                 : valueSearchNonNull(root, value)));
229      }
230  
231      private boolean valueSearchNull(Entry n) {
# Line 236 | Line 234 | public class TreeMap<K,V>
234  
235          // Check left and right subtrees for value
236          return (n.left  != null && valueSearchNull(n.left)) ||
237 <               (n.right != null && valueSearchNull(n.right));
237 >            (n.right != null && valueSearchNull(n.right));
238      }
239  
240      private boolean valueSearchNonNull(Entry n, Object value) {
# Line 246 | Line 244 | public class TreeMap<K,V>
244  
245          // Check left and right subtrees for value
246          return (n.left  != null && valueSearchNonNull(n.left, value)) ||
247 <               (n.right != null && valueSearchNonNull(n.right, value));
247 >            (n.right != null && valueSearchNonNull(n.right, value));
248      }
249  
250      /**
251 <     * Returns the value to which this map maps the specified key.  Returns
252 <     * <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.
251 >     * Returns the value to which the specified key is mapped,
252 >     * or {@code null} if this map contains no mapping for the key.
253       *
254 <     * @see #containsKey(Object)
254 >     * <p>More formally, if this map contains a mapping from a key
255 >     * {@code k} to a value {@code v} such that {@code key} compares
256 >     * equal to {@code k} according to the map's ordering, then this
257 >     * method returns {@code v}; otherwise it returns {@code null}.
258 >     * (There can be at most one such mapping.)
259 >     *
260 >     * <p>A return value of {@code null} does not <i>necessarily</i>
261 >     * indicate that the map contains no mapping for the key; it's also
262 >     * possible that the map explicitly maps the key to {@code null}.
263 >     * The {@link #containsKey containsKey} operation may be used to
264 >     * distinguish these two cases.
265 >     *
266 >     * @throws ClassCastException if the specified key cannot be compared
267 >     *         with the keys currently in the map
268 >     * @throws NullPointerException if the specified key is null
269 >     *         and this map uses natural ordering, or its comparator
270 >     *         does not permit null keys
271       */
272      public V get(Object key) {
273          Entry<K,V> p = getEntry(key);
274          return (p==null ? null : p.value);
275      }
276  
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     */
277      public Comparator<? super K> comparator() {
278          return comparator;
279      }
280  
281      /**
282 <     * 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.
282 >     * @throws NoSuchElementException {@inheritDoc}
283       */
284      public K firstKey() {
285          return key(getFirstEntry());
286      }
287  
288      /**
289 <     * 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.
289 >     * @throws NoSuchElementException {@inheritDoc}
290       */
291      public K lastKey() {
292          return key(getLastEntry());
293      }
294  
295      /**
296 <     * Copies all of the mappings from the specified map to this map.  These
297 <     * mappings replace any mappings that this map had for any of the keys
298 <     * currently in the specified map.
299 <     *
300 <     * @param     map mappings to be stored in this map.
301 <     * @throws    ClassCastException class of a key or value in the specified
302 <     *                   map prevents it from being stored in this map.
303 <     *
304 <     * @throws NullPointerException if the given map is <tt>null</tt> or
305 <     *         this map does not permit <tt>null</tt> keys and a
318 <     *         key in the specified map is <tt>null</tt>.
296 >     * Copies all of the mappings from the specified map to this map.
297 >     * These mappings replace any mappings that this map had for any
298 >     * of the keys currently in the specified map.
299 >     *
300 >     * @param  map mappings to be stored in this map
301 >     * @throws ClassCastException if the class of a key or value in
302 >     *         the specified map prevents it from being stored in this map
303 >     * @throws NullPointerException if the specified map is null or
304 >     *         the specified map contains a null key and this map does not
305 >     *         permit null keys
306       */
307      public void putAll(Map<? extends K, ? extends V> map) {
308          int mapSize = map.size();
# Line 340 | Line 327 | public class TreeMap<K,V>
327       * does not contain an entry for the key.
328       *
329       * @return this map's entry for the given key, or <tt>null</tt> if the map
330 <     *                does not contain an entry for the key.
331 <     * @throws ClassCastException if the key cannot be compared with the keys
332 <     *                  currently in the map.
333 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
334 <     *                  natural order, or its comparator does not tolerate *
335 <     *                  <tt>null</tt> keys.
330 >     *         does not contain an entry for the key
331 >     * @throws ClassCastException if the specified key cannot be compared
332 >     *         with the keys currently in the map
333 >     * @throws NullPointerException if the specified key is null
334 >     *         and this map uses natural ordering, or its comparator
335 >     *         does not permit null keys
336       */
337 <    private Entry<K,V> getEntry(Object key) {
337 >    final Entry<K,V> getEntry(Object key) {
338          // Offload comparator-based version for sake of performance
339          if (comparator != null)
340              return getEntryUsingComparator(key);
341 <        Comparable<K> k = (Comparable<K>) key;
341 >        if (key == null)
342 >            throw new NullPointerException();
343 >        Comparable<? super K> k = (Comparable<? super K>) key;
344          Entry<K,V> p = root;
345          while (p != null) {
346              int cmp = k.compareTo(p.key);
# Line 369 | Line 358 | public class TreeMap<K,V>
358       * Version of getEntry using comparator. Split off from getEntry
359       * for performance. (This is not worth doing for most methods,
360       * that are less dependent on comparator performance, but is
361 <     * worthwhile here.)
361 >     * worthwhile for get and put.)
362       */
363 <    private Entry<K,V> getEntryUsingComparator(Object key) {
363 >    final Entry<K,V> getEntryUsingComparator(Object key) {
364          K k = (K) key;
365          Comparator<? super K> cpr = comparator;
366          Entry<K,V> p = root;
# Line 393 | Line 382 | public class TreeMap<K,V>
382       * key; if no such entry exists (i.e., the greatest key in the Tree is less
383       * than the specified key), returns <tt>null</tt>.
384       */
385 <    private Entry<K,V> getCeilingEntry(K key) {
385 >    final Entry<K,V> getCeilingEntry(K key) {
386          Entry<K,V> p = root;
387 <        if (p==null)
399 <            return null;
400 <
401 <        while (true) {
387 >        while (p != null) {
388              int cmp = compare(key, p.key);
389              if (cmp < 0) {
390                  if (p.left != null)
# Line 420 | Line 406 | public class TreeMap<K,V>
406              } else
407                  return p;
408          }
409 +        return null;
410      }
411  
412      /**
# Line 427 | Line 414 | public class TreeMap<K,V>
414       * exists, returns the entry for the greatest key less than the specified
415       * key; if no such entry exists, returns <tt>null</tt>.
416       */
417 <    private Entry<K,V> getFloorEntry(K key) {
417 >    final Entry<K,V> getFloorEntry(K key) {
418          Entry<K,V> p = root;
419 <        if (p==null)
433 <            return null;
434 <
435 <        while (true) {
419 >        while (p != null) {
420              int cmp = compare(key, p.key);
421              if (cmp > 0) {
422                  if (p.right != null)
# Line 455 | Line 439 | public class TreeMap<K,V>
439                  return p;
440  
441          }
442 +        return null;
443      }
444  
445      /**
# Line 463 | Line 448 | public class TreeMap<K,V>
448       * key greater than the specified key; if no such entry exists
449       * returns <tt>null</tt>.
450       */
451 <    private Entry<K,V> getHigherEntry(K key) {
451 >    final Entry<K,V> getHigherEntry(K key) {
452          Entry<K,V> p = root;
453 <        if (p==null)
469 <            return null;
470 <
471 <        while (true) {
453 >        while (p != null) {
454              int cmp = compare(key, p.key);
455              if (cmp < 0) {
456                  if (p.left != null)
# Line 489 | Line 471 | public class TreeMap<K,V>
471                  }
472              }
473          }
474 +        return null;
475      }
476  
477      /**
# Line 496 | Line 479 | public class TreeMap<K,V>
479       * no such entry exists (i.e., the least key in the Tree is greater than
480       * the specified key), returns <tt>null</tt>.
481       */
482 <    private Entry<K,V> getLowerEntry(K key) {
482 >    final Entry<K,V> getLowerEntry(K key) {
483          Entry<K,V> p = root;
484 <        if (p==null)
502 <            return null;
503 <
504 <        while (true) {
484 >        while (p != null) {
485              int cmp = compare(key, p.key);
486              if (cmp > 0) {
487                  if (p.right != null)
# Line 522 | Line 502 | public class TreeMap<K,V>
502                  }
503              }
504          }
505 <    }
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;
505 >        return null;
506      }
507  
508      /**
509       * Associates the specified value with the specified key in this map.
510 <     * If the map previously contained a mapping for this key, the old
510 >     * If the map previously contained a mapping for the key, the old
511       * value is replaced.
512       *
513 <     * @param key key with which the specified value is to be associated.
514 <     * @param value value to be associated with the specified key.
513 >     * @param key key with which the specified value is to be associated
514 >     * @param value value to be associated with the specified key
515       *
516 <     * @return previous value associated with specified key, or <tt>null</tt>
517 <     *         if there was no mapping for key.  A <tt>null</tt> return can
518 <     *         also indicate that the map previously associated <tt>null</tt>
519 <     *         with the specified key.
520 <     * @throws    ClassCastException key cannot be compared with the keys
521 <     *            currently in the map.
522 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
523 <     *         natural order, or its comparator does not tolerate
524 <     *         <tt>null</tt> keys.
516 >     * @return the previous value associated with <tt>key</tt>, or
517 >     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
518 >     *         (A <tt>null</tt> return can also indicate that the map
519 >     *         previously associated <tt>null</tt> with <tt>key</tt>.)
520 >     * @throws ClassCastException if the specified key cannot be compared
521 >     *         with the keys currently in the map
522 >     * @throws NullPointerException if the specified key is null
523 >     *         and this map uses natural ordering, or its comparator
524 >     *         does not permit null keys
525       */
526      public V put(K key, V value) {
527 +        // Offload comparator-based version for sake of performance
528 +        if (comparator != null)
529 +            return putUsingComparator(key, value);
530 +        if (key == null)
531 +            throw new NullPointerException();
532 +        Comparable<? super K> k = (Comparable<? super K>) key;
533 +        int cmp = 0;
534 +        Entry<K,V> parent = null;
535          Entry<K,V> t = root;
536 +        while (t != null) {
537 +            parent = t;
538 +            cmp = k.compareTo(t.key);
539 +            if (cmp < 0)
540 +                t = t.left;
541 +            else if (cmp > 0)
542 +                t = t.right;
543 +            else
544 +                return t.setValue(value);
545 +        }
546 +        Entry<K,V> e = new Entry<K,V>((K)k, value, parent);
547 +        size++;
548 +        modCount++;
549 +        if (parent != null) {
550 +            if (cmp < 0)
551 +                parent.left = e;
552 +            else
553 +                parent.right = e;
554 +            fixAfterInsertion(e);
555 +        }
556 +        else
557 +            root = e;
558 +        return null;
559 +    }
560  
561 <        if (t == null) {
562 <            incrementSize();
563 <            root = new Entry<K,V>(key, value, null);
564 <            return null;
565 <       }
566 <
567 <        while (true) {
568 <            int cmp = compare(key, t.key);
569 <            if (cmp == 0) {
561 >    /**
562 >     * Version of put using comparator. Split off from put for
563 >     * performance.
564 >     */
565 >    final V putUsingComparator(K key, V value) {
566 >        Comparator<? super K> cpr = comparator;
567 >        int cmp = 0;
568 >        Entry<K,V> parent = null;
569 >        Entry<K,V> t = root;
570 >        if (t == null)
571 >            cpr.compare(key, key); // type check
572 >        while (t != null) {
573 >            parent = t;
574 >            cmp = cpr.compare(key, t.key);
575 >            if (cmp < 0)
576 >                t = t.left;
577 >            else if (cmp > 0)
578 >                t = t.right;
579 >            else
580                  return t.setValue(value);
568            } else if (cmp < 0) {
569                if (t.left != null) {
570                    t = t.left;
571                } 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) {
579                    t = t.right;
580                } else {
581                    incrementSize();
582                    t.right = new Entry<K,V>(key, value, t);
583                    fixAfterInsertion(t.right);
584                    return null;
585                }
586            }
581          }
582 +        Entry<K,V> e = new Entry<K,V>(key, value, parent);
583 +        size++;
584 +        modCount++;
585 +        if (parent != null) {
586 +            if (cmp < 0)
587 +                parent.left = e;
588 +            else
589 +                parent.right = e;
590 +            fixAfterInsertion(e);
591 +        }
592 +        else
593 +            root = e;
594 +        return null;
595      }
596  
597      /**
598       * Removes the mapping for this key from this TreeMap if present.
599       *
600       * @param  key key for which mapping should be removed
601 <     * @return previous value associated with specified key, or <tt>null</tt>
602 <     *         if there was no mapping for key.  A <tt>null</tt> return can
603 <     *         also indicate that the map previously associated
604 <     *         <tt>null</tt> with the specified key.
605 <     *
606 <     * @throws    ClassCastException key cannot be compared with the keys
607 <     *            currently in the map.
608 <     * @throws NullPointerException key is <tt>null</tt> and this map uses
609 <     *         natural order, or its comparator does not tolerate
603 <     *         <tt>null</tt> keys.
601 >     * @return the previous value associated with <tt>key</tt>, or
602 >     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
603 >     *         (A <tt>null</tt> return can also indicate that the map
604 >     *         previously associated <tt>null</tt> with <tt>key</tt>.)
605 >     * @throws ClassCastException if the specified key cannot be compared
606 >     *         with the keys currently in the map
607 >     * @throws NullPointerException if the specified key is null
608 >     *         and this map uses natural ordering, or its comparator
609 >     *         does not permit null keys
610       */
611      public V remove(Object key) {
612          Entry<K,V> p = getEntry(key);
# Line 613 | Line 619 | public class TreeMap<K,V>
619      }
620  
621      /**
622 <     * Removes all mappings from this TreeMap.
622 >     * Removes all of the mappings from this map.
623 >     * The map will be empty after this call returns.
624       */
625      public void clear() {
626          modCount++;
# Line 625 | Line 632 | public class TreeMap<K,V>
632       * Returns a shallow copy of this <tt>TreeMap</tt> instance. (The keys and
633       * values themselves are not cloned.)
634       *
635 <     * @return a shallow copy of this Map.
635 >     * @return a shallow copy of this map
636       */
637      public Object clone() {
638          TreeMap<K,V> clone = null;
# Line 640 | Line 647 | public class TreeMap<K,V>
647          clone.size = 0;
648          clone.modCount = 0;
649          clone.entrySet = null;
650 <        clone.descendingEntrySet = null;
651 <        clone.descendingKeySet = null;
650 >        clone.navigableKeySet = null;
651 >        clone.descendingMap = null;
652  
653          // Initialize clone with our mappings
654          try {
# Line 656 | Line 663 | public class TreeMap<K,V>
663      // NavigableMap API methods
664  
665      /**
666 <     * 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.
666 >     * @since 1.6
667       */
668      public Map.Entry<K,V> firstEntry() {
669 <        Entry<K,V> e = getFirstEntry();
667 <        return (e == null)? null : new SnapshotEntry(e);
669 >        return exportEntry(getFirstEntry());
670      }
671  
672      /**
673 <     * 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.
673 >     * @since 1.6
674       */
675      public Map.Entry<K,V> lastEntry() {
676 <        Entry<K,V> e = getLastEntry();
681 <        return (e == null)? null : new SnapshotEntry(e);
676 >        return exportEntry(getLastEntry());
677      }
678  
679      /**
680 <     * 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.
680 >     * @since 1.6
681       */
682      public Map.Entry<K,V> pollFirstEntry() {
683          Entry<K,V> p = getFirstEntry();
684 <        if (p == null)
685 <            return null;
686 <        Map.Entry result = new SnapshotEntry(p);
696 <        deleteEntry(p);
684 >        Map.Entry<K,V> result = exportEntry(p);
685 >        if (p != null)
686 >            deleteEntry(p);
687          return result;
688      }
689  
690      /**
691 <     * 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.
691 >     * @since 1.6
692       */
693      public Map.Entry<K,V> pollLastEntry() {
694          Entry<K,V> p = getLastEntry();
695 <        if (p == null)
696 <            return null;
697 <        Map.Entry result = new SnapshotEntry(p);
712 <        deleteEntry(p);
695 >        Map.Entry<K,V> result = exportEntry(p);
696 >        if (p != null)
697 >            deleteEntry(p);
698          return result;
699      }
700  
701      /**
702 <     * Returns a key-value mapping associated with the least key
703 <     * greater than or equal to the given key, or <tt>null</tt> if
704 <     * there is no such entry.
705 <     *
706 <     * @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.
702 >     * @throws ClassCastException {@inheritDoc}
703 >     * @throws NullPointerException if the specified key is null
704 >     *         and this map uses natural ordering, or its comparator
705 >     *         does not permit null keys
706 >     * @since 1.6
707       */
708 <    public Map.Entry<K,V> ceilingEntry(K key) {
709 <        Entry<K,V> e = getCeilingEntry(key);
732 <        return (e == null)? null : new SnapshotEntry(e);
708 >    public Map.Entry<K,V> lowerEntry(K key) {
709 >        return exportEntry(getLowerEntry(key));
710      }
711  
735
712      /**
713 <     * Returns least key greater than or equal to the given key, or
714 <     * <tt>null</tt> if there is no such key.
715 <     *
716 <     * @param key the key.
717 <     * @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.
713 >     * @throws ClassCastException {@inheritDoc}
714 >     * @throws NullPointerException if the specified key is null
715 >     *         and this map uses natural ordering, or its comparator
716 >     *         does not permit null keys
717 >     * @since 1.6
718       */
719 <    public K ceilingKey(K key) {
720 <        Entry<K,V> e = getCeilingEntry(key);
751 <        return (e == null)? null : e.key;
719 >    public K lowerKey(K key) {
720 >        return keyOrNull(getLowerEntry(key));
721      }
722  
754
755
723      /**
724 <     * Returns a key-value mapping associated with the greatest key
725 <     * less than or equal to the given key, or <tt>null</tt> if there
726 <     * is no such entry.
727 <     *
728 <     * @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.
724 >     * @throws ClassCastException {@inheritDoc}
725 >     * @throws NullPointerException if the specified key is null
726 >     *         and this map uses natural ordering, or its comparator
727 >     *         does not permit null keys
728 >     * @since 1.6
729       */
730      public Map.Entry<K,V> floorEntry(K key) {
731 <        Entry<K,V> e = getFloorEntry(key);
772 <        return (e == null)? null : new SnapshotEntry(e);
731 >        return exportEntry(getFloorEntry(key));
732      }
733  
734      /**
735 <     * Returns the greatest key
736 <     * less than or equal to the given key, or <tt>null</tt> if there
737 <     * is no such key.
738 <     *
739 <     * @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.
735 >     * @throws ClassCastException {@inheritDoc}
736 >     * @throws NullPointerException if the specified key is null
737 >     *         and this map uses natural ordering, or its comparator
738 >     *         does not permit null keys
739 >     * @since 1.6
740       */
741      public K floorKey(K key) {
742 <        Entry<K,V> e = getFloorEntry(key);
791 <        return (e == null)? null : e.key;
742 >        return keyOrNull(getFloorEntry(key));
743      }
744  
745      /**
746 <     * Returns a key-value mapping associated with the least key
747 <     * strictly greater than the given key, or <tt>null</tt> if there
748 <     * is no such entry.
749 <     *
750 <     * @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.
746 >     * @throws ClassCastException {@inheritDoc}
747 >     * @throws NullPointerException if the specified key is null
748 >     *         and this map uses natural ordering, or its comparator
749 >     *         does not permit null keys
750 >     * @since 1.6
751       */
752 <    public Map.Entry<K,V> higherEntry(K key) {
753 <        Entry<K,V> e = getHigherEntry(key);
810 <        return (e == null)? null : new SnapshotEntry(e);
752 >    public Map.Entry<K,V> ceilingEntry(K key) {
753 >        return exportEntry(getCeilingEntry(key));
754      }
755  
756      /**
757 <     * Returns the least key strictly greater than the given key, or
758 <     * <tt>null</tt> if there is no such key.
759 <     *
760 <     * @param key the key.
761 <     * @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.
757 >     * @throws ClassCastException {@inheritDoc}
758 >     * @throws NullPointerException if the specified key is null
759 >     *         and this map uses natural ordering, or its comparator
760 >     *         does not permit null keys
761 >     * @since 1.6
762       */
763 <    public K higherKey(K key) {
764 <        Entry<K,V> e = getHigherEntry(key);
828 <        return (e == null)? null : e.key;
763 >    public K ceilingKey(K key) {
764 >        return keyOrNull(getCeilingEntry(key));
765      }
766  
767      /**
768 <     * Returns a key-value mapping associated with the greatest
769 <     * key strictly less than the given key, or <tt>null</tt> if there is no
770 <     * such entry.
771 <     *
772 <     * @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.
768 >     * @throws ClassCastException {@inheritDoc}
769 >     * @throws NullPointerException if the specified key is null
770 >     *         and this map uses natural ordering, or its comparator
771 >     *         does not permit null keys
772 >     * @since 1.6
773       */
774 <    public Map.Entry<K,V> lowerEntry(K key) {
775 <        Entry<K,V> e =  getLowerEntry(key);
847 <        return (e == null)? null : new SnapshotEntry(e);
774 >    public Map.Entry<K,V> higherEntry(K key) {
775 >        return exportEntry(getHigherEntry(key));
776      }
777  
778      /**
779 <     * Returns the greatest key strictly less than the given key, or
780 <     * <tt>null</tt> if there is no such key.
781 <     *
782 <     * @param key the key.
783 <     * @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.
779 >     * @throws ClassCastException {@inheritDoc}
780 >     * @throws NullPointerException if the specified key is null
781 >     *         and this map uses natural ordering, or its comparator
782 >     *         does not permit null keys
783 >     * @since 1.6
784       */
785 <    public K lowerKey(K key) {
786 <        Entry<K,V> e =  getLowerEntry(key);
865 <        return (e == null)? null : e.key;
785 >    public K higherKey(K key) {
786 >        return keyOrNull(getHigherEntry(key));
787      }
788  
789      // Views
# Line 872 | Line 793 | public class TreeMap<K,V>
793       * the first time this view is requested.  Views are stateless, so
794       * there's no reason to create more than one.
795       */
796 <    private transient Set<Map.Entry<K,V>> entrySet = null;
797 <    private transient Set<Map.Entry<K,V>> descendingEntrySet = null;
798 <    private transient Set<K> descendingKeySet = null;
799 <
800 <    transient Set<K> keySet = null;        // XXX remove when integrated
801 <    transient Collection<V> values = null; // XXX remove when integrated
802 <
803 <    /**
804 <     * Returns a Set view of the keys contained in this map.  The set's
805 <     * iterator will return the keys in ascending order.  The set is backed by
806 <     * this <tt>TreeMap</tt> instance, so changes to this map are reflected in
807 <     * the Set, and vice-versa.  The Set supports element removal, which
808 <     * removes the corresponding mapping from the map, via the
809 <     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>,
810 <     * <tt>retainAll</tt>, and <tt>clear</tt> operations.  It does not support
811 <     * the <tt>add</tt> or <tt>addAll</tt> operations.
812 <     *
892 <     * @return a set view of the keys contained in this TreeMap.
796 >    private transient EntrySet entrySet = null;
797 >    private transient KeySet<K> navigableKeySet = null;
798 >    private transient NavigableMap<K,V> descendingMap = null;
799 >
800 >    /**
801 >     * Returns a {@link Set} view of the keys contained in this map.
802 >     * The set's iterator returns the keys in ascending order.
803 >     * The set is backed by the map, so changes to the map are
804 >     * reflected in the set, and vice-versa.  If the map is modified
805 >     * while an iteration over the set is in progress (except through
806 >     * the iterator's own <tt>remove</tt> operation), the results of
807 >     * the iteration are undefined.  The set supports element removal,
808 >     * which removes the corresponding mapping from the map, via the
809 >     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
810 >     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
811 >     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
812 >     * operations.
813       */
814      public Set<K> keySet() {
815 <        Set<K> ks = keySet;
896 <        return (ks != null) ? ks : (keySet = new KeySet());
815 >        return navigableKeySet();
816      }
817  
818 <    class KeySet extends AbstractSet<K> {
819 <        public Iterator<K> iterator() {
820 <            return new KeyIterator(getFirstEntry());
821 <        }
822 <        
823 <        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 <        }
818 >    /**
819 >     * @since 1.6
820 >     */
821 >    public NavigableSet<K> navigableKeySet() {
822 >        KeySet<K> nks = navigableKeySet;
823 >        return (nks != null) ? nks : (navigableKeySet = new KeySet(this));
824      }
825  
826      /**
827 <     * Returns a collection view of the values contained in this map.  The
828 <     * collection's iterator will return the values in the order that their
829 <     * corresponding keys appear in the tree.  The collection is backed by
830 <     * this <tt>TreeMap</tt> instance, so changes to this map are reflected in
831 <     * the collection, and vice-versa.  The collection supports element
832 <     * removal, which removes the corresponding mapping from the map through
833 <     * the <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
834 <     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
835 <     * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
836 <     *
837 <     * @return a collection view of the values contained in this map.
827 >     * @since 1.6
828 >     */
829 >    public NavigableSet<K> descendingKeySet() {
830 >        return descendingMap().navigableKeySet();
831 >    }
832 >
833 >    /**
834 >     * Returns a {@link Collection} view of the values contained in this map.
835 >     * The collection's iterator returns the values in ascending order
836 >     * of the corresponding keys.
837 >     * The collection is backed by the map, so changes to the map are
838 >     * reflected in the collection, and vice-versa.  If the map is
839 >     * modified while an iteration over the collection is in progress
840 >     * (except through the iterator's own <tt>remove</tt> operation),
841 >     * the results of the iteration are undefined.  The collection
842 >     * supports element removal, which removes the corresponding
843 >     * mapping from the map, via the <tt>Iterator.remove</tt>,
844 >     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
845 >     * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
846 >     * support the <tt>add</tt> or <tt>addAll</tt> operations.
847       */
848      public Collection<V> values() {
849          Collection<V> vs = values;
850          return (vs != null) ? vs : (values = new Values());
851      }
852  
853 +    /**
854 +     * Returns a {@link Set} view of the mappings contained in this map.
855 +     * The set's iterator returns the entries in ascending key order.
856 +     * The set is backed by the map, so changes to the map are
857 +     * reflected in the set, and vice-versa.  If the map is modified
858 +     * while an iteration over the set is in progress (except through
859 +     * the iterator's own <tt>remove</tt> operation, or through the
860 +     * <tt>setValue</tt> operation on a map entry returned by the
861 +     * iterator) the results of the iteration are undefined.  The set
862 +     * supports element removal, which removes the corresponding
863 +     * mapping from the map, via the <tt>Iterator.remove</tt>,
864 +     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
865 +     * <tt>clear</tt> operations.  It does not support the
866 +     * <tt>add</tt> or <tt>addAll</tt> operations.
867 +     */
868 +    public Set<Map.Entry<K,V>> entrySet() {
869 +        EntrySet es = entrySet;
870 +        return (es != null) ? es : (entrySet = new EntrySet());
871 +    }
872 +
873 +    /**
874 +     * @since 1.6
875 +     */
876 +    public NavigableMap<K, V> descendingMap() {
877 +        NavigableMap<K, V> km = descendingMap;
878 +        return (km != null) ? km :
879 +            (descendingMap = new DescendingSubMap(this,
880 +                                                  true, null, true,
881 +                                                  true, null, true));
882 +    }
883 +
884 +    /**
885 +     * @throws ClassCastException       {@inheritDoc}
886 +     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
887 +     *         null and this map uses natural ordering, or its comparator
888 +     *         does not permit null keys
889 +     * @throws IllegalArgumentException {@inheritDoc}
890 +     * @since 1.6
891 +     */
892 +    public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
893 +                                    K toKey,   boolean toInclusive) {
894 +        return new AscendingSubMap(this,
895 +                                   false, fromKey, fromInclusive,
896 +                                   false, toKey,   toInclusive);
897 +    }
898 +
899 +    /**
900 +     * @throws ClassCastException       {@inheritDoc}
901 +     * @throws NullPointerException if <tt>toKey</tt> is null
902 +     *         and this map uses natural ordering, or its comparator
903 +     *         does not permit null keys
904 +     * @throws IllegalArgumentException {@inheritDoc}
905 +     * @since 1.6
906 +     */
907 +    public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
908 +        return new AscendingSubMap(this,
909 +                                   true,  null,  true,
910 +                                   false, toKey, inclusive);
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 +     * @since 1.6
920 +     */
921 +    public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
922 +        return new AscendingSubMap(this,
923 +                                   false, fromKey, inclusive,
924 +                                   true,  null,    true);
925 +    }
926 +
927 +    /**
928 +     * @throws ClassCastException       {@inheritDoc}
929 +     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
930 +     *         null and this map uses natural ordering, or its comparator
931 +     *         does not permit null keys
932 +     * @throws IllegalArgumentException {@inheritDoc}
933 +     */
934 +    public SortedMap<K,V> subMap(K fromKey, K toKey) {
935 +        return subMap(fromKey, true, toKey, false);
936 +    }
937 +
938 +    /**
939 +     * @throws ClassCastException       {@inheritDoc}
940 +     * @throws NullPointerException if <tt>toKey</tt> is null
941 +     *         and this map uses natural ordering, or its comparator
942 +     *         does not permit null keys
943 +     * @throws IllegalArgumentException {@inheritDoc}
944 +     */
945 +    public SortedMap<K,V> headMap(K toKey) {
946 +        return headMap(toKey, false);
947 +    }
948 +
949 +    /**
950 +     * @throws ClassCastException       {@inheritDoc}
951 +     * @throws NullPointerException if <tt>fromKey</tt> is null
952 +     *         and this map uses natural ordering, or its comparator
953 +     *         does not permit null keys
954 +     * @throws IllegalArgumentException {@inheritDoc}
955 +     */
956 +    public SortedMap<K,V> tailMap(K fromKey) {
957 +        return tailMap(fromKey, true);
958 +    }
959 +
960 +    // View class support
961 +
962      class Values extends AbstractCollection<V> {
963          public Iterator<V> iterator() {
964              return new ValueIterator(getFirstEntry());
965          }
966 <        
966 >
967          public int size() {
968              return TreeMap.this.size();
969          }
970 <        
970 >
971          public boolean contains(Object o) {
972              for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
973                  if (valEquals(e.getValue(), o))
974                      return true;
975              return false;
976          }
977 <        
977 >
978          public boolean remove(Object o) {
979              for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
980                  if (valEquals(e.getValue(), o)) {
# Line 963 | Line 984 | public class TreeMap<K,V>
984              }
985              return false;
986          }
987 <        
987 >
988          public void clear() {
989              TreeMap.this.clear();
990          }
991      }
992  
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
993      class EntrySet extends AbstractSet<Map.Entry<K,V>> {
994          public Iterator<Map.Entry<K,V>> iterator() {
995              return new EntryIterator(getFirstEntry());
996          }
997 <        
997 >
998          public boolean contains(Object o) {
999              if (!(o instanceof Map.Entry))
1000                  return false;
# Line 1001 | Line 1003 | public class TreeMap<K,V>
1003              Entry<K,V> p = getEntry(entry.getKey());
1004              return p != null && valEquals(p.getValue(), value);
1005          }
1006 <        
1006 >
1007          public boolean remove(Object o) {
1008              if (!(o instanceof Map.Entry))
1009                  return false;
# Line 1014 | Line 1016 | public class TreeMap<K,V>
1016              }
1017              return false;
1018          }
1019 <        
1019 >
1020          public int size() {
1021              return TreeMap.this.size();
1022          }
1023 <        
1023 >
1024          public void clear() {
1025              TreeMap.this.clear();
1026          }
1027      }
1028  
1029 <    /**
1030 <     * Returns a set view of the mappings contained in this map.  The
1031 <     * set's iterator returns the mappings in descrending key order.
1032 <     * Each element in the returned set is a <tt>Map.Entry</tt>.  The
1033 <     * set is backed by this map, so changes to this map are reflected
1034 <     * in the set, and vice-versa.  The set supports element removal,
1035 <     * which removes the corresponding mapping from the TreeMap,
1036 <     * through the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1037 <     * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
1038 <     * 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());
1029 >    /*
1030 >     * Unlike Values and EntrySet, the KeySet class is static,
1031 >     * delegating to a NavigableMap to allow use by SubMaps, which
1032 >     * outweighs the ugliness of needing type-tests for the following
1033 >     * Iterator methods that are defined appropriately in main versus
1034 >     * submap classes.
1035 >     */
1036 >
1037 >    Iterator<K> keyIterator() {
1038 >        return new KeyIterator(getFirstEntry());
1039      }
1040  
1041 <    class DescendingEntrySet extends EntrySet {
1042 <        public Iterator<Map.Entry<K,V>> iterator() {
1043 <            return new DescendingEntryIterator(getLastEntry());
1041 >    Iterator<K> descendingKeyIterator() {
1042 >        return new DescendingKeyIterator(getFirstEntry());
1043 >    }
1044 >
1045 >    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
1046 >        private final NavigableMap<E, Object> m;
1047 >        KeySet(NavigableMap<E,Object> map) { m = map; }
1048 >
1049 >        public Iterator<E> iterator() {
1050 >            if (m instanceof TreeMap)
1051 >                return ((TreeMap<E,Object>)m).keyIterator();
1052 >            else
1053 >                return (Iterator<E>)(((TreeMap.NavigableSubMap)m).keyIterator());
1054 >        }
1055 >
1056 >        public Iterator<E> descendingIterator() {
1057 >            if (m instanceof TreeMap)
1058 >                return ((TreeMap<E,Object>)m).descendingKeyIterator();
1059 >            else
1060 >                return (Iterator<E>)(((TreeMap.NavigableSubMap)m).descendingKeyIterator());
1061 >        }
1062 >
1063 >        public int size() { return m.size(); }
1064 >        public boolean isEmpty() { return m.isEmpty(); }
1065 >        public boolean contains(Object o) { return m.containsKey(o); }
1066 >        public void clear() { m.clear(); }
1067 >        public E lower(E e) { return m.lowerKey(e); }
1068 >        public E floor(E e) { return m.floorKey(e); }
1069 >        public E ceiling(E e) { return m.ceilingKey(e); }
1070 >        public E higher(E e) { return m.higherKey(e); }
1071 >        public E first() { return m.firstKey(); }
1072 >        public E last() { return m.lastKey(); }
1073 >        public Comparator<? super E> comparator() { return m.comparator(); }
1074 >        public E pollFirst() {
1075 >            Map.Entry<E,Object> e = m.pollFirstEntry();
1076 >            return e == null? null : e.getKey();
1077 >        }
1078 >        public E pollLast() {
1079 >            Map.Entry<E,Object> e = m.pollLastEntry();
1080 >            return e == null? null : e.getKey();
1081 >        }
1082 >        public boolean remove(Object o) {
1083 >            int oldSize = size();
1084 >            m.remove(o);
1085 >            return size() != oldSize;
1086 >        }
1087 >        public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
1088 >                                      E toElement, boolean toInclusive) {
1089 >            return new TreeSet<E>(m.subMap(fromElement, fromInclusive,
1090 >                                           toElement,   toInclusive));
1091 >        }
1092 >        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1093 >            return new TreeSet<E>(m.headMap(toElement, inclusive));
1094 >        }
1095 >        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1096 >            return new TreeSet<E>(m.tailMap(fromElement, inclusive));
1097 >        }
1098 >        public SortedSet<E> subSet(E fromElement, E toElement) {
1099 >            return subSet(fromElement, true, toElement, false);
1100 >        }
1101 >        public SortedSet<E> headSet(E toElement) {
1102 >            return headSet(toElement, false);
1103 >        }
1104 >        public SortedSet<E> tailSet(E fromElement) {
1105 >            return tailSet(fromElement, true);
1106 >        }
1107 >        public NavigableSet<E> descendingSet() {
1108 >            return new TreeSet(m.descendingMap());
1109          }
1110      }
1111  
1112      /**
1113 <     * 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.
1113 >     * Base class for TreeMap Iterators
1114       */
1115 <    public Set<K> descendingKeySet() {
1116 <        Set<K> ks = descendingKeySet;
1117 <        return (ks != null) ? ks : (descendingKeySet = new DescendingKeySet());
1118 <    }
1119 <
1120 <    class DescendingKeySet extends KeySet {
1121 <        public Iterator<K> iterator() {
1122 <            return new DescendingKeyIterator(getLastEntry());
1115 >    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1116 >        Entry<K,V> next;
1117 >        Entry<K,V> lastReturned;
1118 >        int expectedModCount;
1119 >
1120 >        PrivateEntryIterator(Entry<K,V> first) {
1121 >            expectedModCount = modCount;
1122 >            lastReturned = null;
1123 >            next = first;
1124 >        }
1125 >
1126 >        public final boolean hasNext() {
1127 >            return next != null;
1128 >        }
1129 >
1130 >        final Entry<K,V> nextEntry() {
1131 >            Entry<K,V> e = lastReturned = next;
1132 >            if (e == null)
1133 >                throw new NoSuchElementException();
1134 >            if (modCount != expectedModCount)
1135 >                throw new ConcurrentModificationException();
1136 >            next = successor(e);
1137 >            return e;
1138 >        }
1139 >
1140 >        final Entry<K,V> prevEntry() {
1141 >            Entry<K,V> e = lastReturned= next;
1142 >            if (e == null)
1143 >                throw new NoSuchElementException();
1144 >            if (modCount != expectedModCount)
1145 >                throw new ConcurrentModificationException();
1146 >            next = predecessor(e);
1147 >            return e;
1148 >        }
1149 >
1150 >        public void remove() {
1151 >            if (lastReturned == null)
1152 >                throw new IllegalStateException();
1153 >            if (modCount != expectedModCount)
1154 >                throw new ConcurrentModificationException();
1155 >            if (lastReturned.left != null && lastReturned.right != null)
1156 >                next = lastReturned;
1157 >            deleteEntry(lastReturned);
1158 >            expectedModCount++;
1159 >            lastReturned = null;
1160 >        }
1161 >    }
1162 >
1163 >    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1164 >        EntryIterator(Entry<K,V> first) {
1165 >            super(first);
1166 >        }
1167 >        public Map.Entry<K,V> next() {
1168 >            return nextEntry();
1169 >        }
1170 >    }
1171 >
1172 >    final class ValueIterator extends PrivateEntryIterator<V> {
1173 >        ValueIterator(Entry<K,V> first) {
1174 >            super(first);
1175 >        }
1176 >        public V next() {
1177 >            return nextEntry().value;
1178 >        }
1179 >    }
1180 >
1181 >    final class KeyIterator extends PrivateEntryIterator<K> {
1182 >        KeyIterator(Entry<K,V> first) {
1183 >            super(first);
1184 >        }
1185 >        public K next() {
1186 >            return nextEntry().key;
1187 >        }
1188 >    }
1189 >
1190 >    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1191 >        DescendingKeyIterator(Entry<K,V> first) {
1192 >            super(first);
1193 >        }
1194 >        public K next() {
1195 >            return prevEntry().key;
1196          }
1197      }
1198  
1199 +    // Little utilities
1200 +
1201      /**
1202 <     * 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.
1202 >     * Compares two keys using the correct comparison method for this TreeMap.
1203       */
1204 <    public NavigableMap<K,V> subMap(K fromKey, K toKey) {
1205 <        return new SubMap(fromKey, toKey);
1204 >    final int compare(Object k1, Object k2) {
1205 >        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1206 >            : comparator.compare((K)k1, (K)k2);
1207      }
1208  
1209      /**
1210 <     * Returns a view of the portion of this map whose keys are strictly less
1211 <     * than <tt>toKey</tt>.  The returned sorted map is backed by this map, so
1212 <     * changes in the returned sorted map are reflected in this map, and
1213 <     * vice-versa.  The returned sorted map supports all optional map
1214 <     * operations.<p>
1215 <     *
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;
1210 >     * Test two values for equality.  Differs from o1.equals(o2) only in
1211 >     * that it copes with <tt>null</tt> o1 properly.
1212 >     */
1213 >    final static boolean valEquals(Object o1, Object o2) {
1214 >        return (o1==null ? o2==null : o1.equals(o2));
1215 >    }
1216  
1217 <        /**
1218 <         * fromKey is significant only if fromStart is false.  Similarly,
1219 <         * toKey is significant only if toStart is false.
1217 >    /**
1218 >     * Return SimpleImmutableEntry for entry, or null if null
1219 >     */
1220 >    static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
1221 >        return e == null? null :
1222 >            new AbstractMap.SimpleImmutableEntry<K,V>(e);
1223 >    }
1224 >
1225 >    /**
1226 >     * Return key for entry, or null if null
1227 >     */
1228 >    static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
1229 >        return e == null? null : e.key;
1230 >    }
1231 >
1232 >    /**
1233 >     * Returns the key corresponding to the specified Entry.
1234 >     * @throws NoSuchElementException if the Entry is null
1235 >     */
1236 >    static <K> K key(Entry<K,?> e) {
1237 >        if (e==null)
1238 >            throw new NoSuchElementException();
1239 >        return e.key;
1240 >    }
1241 >
1242 >
1243 >    // SubMaps
1244 >
1245 >    static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
1246 >        implements NavigableMap<K,V>, java.io.Serializable {
1247 >        /*
1248 >         * The backing map.
1249           */
1250 <        private boolean fromStart = false, toEnd = false;
1216 <        private K fromKey, toKey;
1250 >        final TreeMap<K,V> m;
1251  
1252 <        SubMap(K fromKey, K toKey) {
1253 <            if (compare(fromKey, toKey) > 0)
1254 <                throw new IllegalArgumentException("fromKey > toKey");
1255 <            this.fromKey = fromKey;
1256 <            this.toKey = toKey;
1257 <        }
1252 >        /*
1253 >         * Endpoints are represented as triples (fromStart, lo,
1254 >         * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is
1255 >         * true, then the low (absolute) bound is the start of the
1256 >         * backing map, and the other values are ignored. Otherwise,
1257 >         * if loInclusive is true, lo is the inclusive bound, else lo
1258 >         * is the exclusive bound. Similarly for the upper bound.
1259 >         */
1260  
1261 <        SubMap(K key, boolean headMap) {
1262 <            compare(key, key); // Type-check key
1263 <
1264 <            if (headMap) {
1265 <                fromStart = true;
1266 <                toKey = key;
1261 >        final K lo, hi;
1262 >        final boolean fromStart, toEnd;
1263 >        final boolean loInclusive, hiInclusive;
1264 >
1265 >        NavigableSubMap(TreeMap<K,V> m,
1266 >                        boolean fromStart, K lo, boolean loInclusive,
1267 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1268 >            if (!fromStart && !toEnd) {
1269 >                if (m.compare(lo, hi) > 0)
1270 >                    throw new IllegalArgumentException("fromKey > toKey");
1271              } else {
1272 <                toEnd = true;
1273 <                fromKey = key;
1272 >                if (!fromStart) // type check
1273 >                    m.compare(lo, lo);
1274 >                if (!toEnd)
1275 >                    m.compare(hi, hi);
1276              }
1235        }
1277  
1278 <        SubMap(boolean fromStart, K fromKey, boolean toEnd, K toKey) {
1278 >            this.m = m;
1279              this.fromStart = fromStart;
1280 <            this.fromKey= fromKey;
1280 >            this.lo = lo;
1281 >            this.loInclusive = loInclusive;
1282              this.toEnd = toEnd;
1283 <            this.toKey = toKey;
1283 >            this.hi = hi;
1284 >            this.hiInclusive = hiInclusive;
1285 >        }
1286 >
1287 >        // internal utilities
1288 >
1289 >        final boolean tooLow(Object key) {
1290 >            if (!fromStart) {
1291 >                int c = m.compare(key, lo);
1292 >                if (c < 0 || (c == 0 && !loInclusive))
1293 >                    return true;
1294 >            }
1295 >            return false;
1296 >        }
1297 >
1298 >        final boolean tooHigh(Object key) {
1299 >            if (!toEnd) {
1300 >                int c = m.compare(key, hi);
1301 >                if (c > 0 || (c == 0 && !hiInclusive))
1302 >                    return true;
1303 >            }
1304 >            return false;
1305 >        }
1306 >
1307 >        final boolean inRange(Object key) {
1308 >            return !tooLow(key) && !tooHigh(key);
1309 >        }
1310 >
1311 >        final boolean inClosedRange(Object key) {
1312 >            return (fromStart || m.compare(key, lo) >= 0)
1313 >                && (toEnd || m.compare(hi, key) >= 0);
1314 >        }
1315 >
1316 >        final boolean inRange(Object key, boolean inclusive) {
1317 >            return inclusive ? inRange(key) : inClosedRange(key);
1318 >        }
1319 >
1320 >        /*
1321 >         * Absolute versions of relation operations.
1322 >         * Subclasses map to these using like-named "sub"
1323 >         * versions that invert senses for descending maps
1324 >         */
1325 >
1326 >        final TreeMap.Entry<K,V> absLowest() {
1327 >            TreeMap.Entry<K,V> e =
1328 >                (fromStart ?  m.getFirstEntry() :
1329 >                 (loInclusive ? m.getCeilingEntry(lo) :
1330 >                                m.getHigherEntry(lo)));
1331 >            return (e == null || tooHigh(e.key)) ? null : e;
1332          }
1333  
1334 +        final TreeMap.Entry<K,V> absHighest() {
1335 +            TreeMap.Entry<K,V> e =
1336 +                (toEnd ?  m.getLastEntry() :
1337 +                 (hiInclusive ?  m.getFloorEntry(hi) :
1338 +                                 m.getLowerEntry(hi)));
1339 +            return (e == null || tooLow(e.key)) ? null : e;
1340 +        }
1341 +
1342 +        final TreeMap.Entry<K,V> absCeiling(K key) {
1343 +            if (tooLow(key))
1344 +                return absLowest();
1345 +            TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
1346 +            return (e == null || tooHigh(e.key)) ? null : e;
1347 +        }
1348 +
1349 +        final TreeMap.Entry<K,V> absHigher(K key) {
1350 +            if (tooLow(key))
1351 +                return absLowest();
1352 +            TreeMap.Entry<K,V> e = m.getHigherEntry(key);
1353 +            return (e == null || tooHigh(e.key)) ? null : e;
1354 +        }
1355 +
1356 +        final TreeMap.Entry<K,V> absFloor(K key) {
1357 +            if (tooHigh(key))
1358 +                return absHighest();
1359 +            TreeMap.Entry<K,V> e = m.getFloorEntry(key);
1360 +            return (e == null || tooLow(e.key)) ? null : e;
1361 +        }
1362 +
1363 +        final TreeMap.Entry<K,V> absLower(K key) {
1364 +            if (tooHigh(key))
1365 +                return absHighest();
1366 +            TreeMap.Entry<K,V> e = m.getLowerEntry(key);
1367 +            return (e == null || tooLow(e.key)) ? null : e;
1368 +        }
1369 +
1370 +        /** Returns the absolute high fence for ascending traversal */
1371 +        final TreeMap.Entry<K,V> absHighFence() {
1372 +            return (toEnd ? null : (hiInclusive ?
1373 +                                    m.getHigherEntry(hi) :
1374 +                                    m.getCeilingEntry(hi)));
1375 +        }
1376 +
1377 +        /** Return the absolute low fence for descending traversal  */
1378 +        final TreeMap.Entry<K,V> absLowFence() {
1379 +            return (fromStart ? null : (loInclusive ?
1380 +                                        m.getLowerEntry(lo) :
1381 +                                        m.getFloorEntry(lo)));
1382 +        }
1383 +
1384 +        // Abstract methods defined in ascending vs descending classes
1385 +        // These relay to the appropriate  absolute versions
1386 +
1387 +        abstract TreeMap.Entry<K,V> subLowest();
1388 +        abstract TreeMap.Entry<K,V> subHighest();
1389 +        abstract TreeMap.Entry<K,V> subCeiling(K key);
1390 +        abstract TreeMap.Entry<K,V> subHigher(K key);
1391 +        abstract TreeMap.Entry<K,V> subFloor(K key);
1392 +        abstract TreeMap.Entry<K,V> subLower(K key);
1393 +
1394 +        /** Returns ascending iterator from the perspective of this submap */
1395 +        abstract Iterator<K> keyIterator();
1396 +
1397 +        /** Returns descending iterator from the perspective of this submap */
1398 +        abstract Iterator<K> descendingKeyIterator();
1399 +
1400 +        // public methods
1401 +
1402          public boolean isEmpty() {
1403 <            return entrySet.isEmpty();
1403 >            return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1404          }
1405  
1406 <        public boolean containsKey(Object key) {
1407 <            return inRange((K) key) && TreeMap.this.containsKey(key);
1406 >        public int size() {
1407 >            return (fromStart && toEnd) ? m.size() : entrySet().size();
1408          }
1409  
1410 <        public V get(Object key) {
1411 <            if (!inRange((K) key))
1254 <                return null;
1255 <            return TreeMap.this.get(key);
1410 >        public final boolean containsKey(Object key) {
1411 >            return inRange(key) && m.containsKey(key);
1412          }
1413  
1414 <        public V put(K key, V value) {
1414 >        public final V put(K key, V value) {
1415              if (!inRange(key))
1416                  throw new IllegalArgumentException("key out of range");
1417 <            return TreeMap.this.put(key, value);
1417 >            return m.put(key, value);
1418          }
1419  
1420 <        public V remove(Object key) {
1421 <            if (!inRange((K) key))
1266 <                return null;
1267 <            return TreeMap.this.remove(key);
1420 >        public final V get(Object key) {
1421 >            return !inRange(key)? null :  m.get(key);
1422          }
1423  
1424 <        public Comparator<? super K> comparator() {
1425 <            return comparator;
1424 >        public final V remove(Object key) {
1425 >            return !inRange(key)? null  : m.remove(key);
1426          }
1427  
1428 <        public K firstKey() {
1429 <            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;
1428 >        public final Map.Entry<K,V> ceilingEntry(K key) {
1429 >            return exportEntry(subCeiling(key));
1430          }
1431  
1432 <        public Map.Entry<K,V> lastEntry() {
1433 <            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;
1432 >        public final K ceilingKey(K key) {
1433 >            return keyOrNull(subCeiling(key));
1434          }
1435  
1436 <        public Map.Entry<K,V> pollFirstEntry() {
1437 <            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;
1436 >        public final Map.Entry<K,V> higherEntry(K key) {
1437 >            return exportEntry(subHigher(key));
1438          }
1439  
1440 <        public Map.Entry<K,V> pollLastEntry() {
1441 <            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;
1440 >        public final K higherKey(K key) {
1441 >            return keyOrNull(subHigher(key));
1442          }
1443  
1444 <        private TreeMap.Entry<K,V> subceiling(K key) {
1445 <            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;
1444 >        public final Map.Entry<K,V> floorEntry(K key) {
1445 >            return exportEntry(subFloor(key));
1446          }
1447  
1448 <        public Map.Entry<K,V> ceilingEntry(K key) {
1449 <            TreeMap.Entry<K,V> e = subceiling(key);
1336 <            return e == null? null : new SnapshotEntry(e);
1448 >        public final K floorKey(K key) {
1449 >            return keyOrNull(subFloor(key));
1450          }
1451  
1452 <        public K ceilingKey(K key) {
1453 <            TreeMap.Entry<K,V> e = subceiling(key);
1341 <            return e == null? null : e.key;
1452 >        public final Map.Entry<K,V> lowerEntry(K key) {
1453 >            return exportEntry(subLower(key));
1454          }
1455  
1456 +        public final K lowerKey(K key) {
1457 +            return keyOrNull(subLower(key));
1458 +        }
1459  
1460 <        private TreeMap.Entry<K,V> subhigher(K key) {
1461 <            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;
1460 >        public final K firstKey() {
1461 >            return key(subLowest());
1462          }
1463  
1464 <        public Map.Entry<K,V> higherEntry(K key) {
1465 <            TreeMap.Entry<K,V> e = subhigher(key);
1355 <            return e == null? null : new SnapshotEntry(e);
1464 >        public final K lastKey() {
1465 >            return key(subHighest());
1466          }
1467  
1468 <        public K higherKey(K key) {
1469 <            TreeMap.Entry<K,V> e = subhigher(key);
1360 <            return e == null? null : e.key;
1468 >        public final Map.Entry<K,V> firstEntry() {
1469 >            return exportEntry(subLowest());
1470          }
1471  
1472 <        private TreeMap.Entry<K,V> subfloor(K key) {
1473 <            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;
1472 >        public final Map.Entry<K,V> lastEntry() {
1473 >            return exportEntry(subHighest());
1474          }
1475  
1476 <        public Map.Entry<K,V> floorEntry(K key) {
1477 <            TreeMap.Entry<K,V> e = subfloor(key);
1478 <            return e == null? null : new SnapshotEntry(e);
1476 >        public final Map.Entry<K,V> pollFirstEntry() {
1477 >            TreeMap.Entry<K,V> e = subLowest();
1478 >            Map.Entry<K,V> result = exportEntry(e);
1479 >            if (e != null)
1480 >                m.deleteEntry(e);
1481 >            return result;
1482          }
1483  
1484 <        public K floorKey(K key) {
1485 <            TreeMap.Entry<K,V> e = subfloor(key);
1486 <            return e == null? null : e.key;
1484 >        public final Map.Entry<K,V> pollLastEntry() {
1485 >            TreeMap.Entry<K,V> e = subHighest();
1486 >            Map.Entry<K,V> result = exportEntry(e);
1487 >            if (e != null)
1488 >                m.deleteEntry(e);
1489 >            return result;
1490          }
1491  
1492 <        private TreeMap.Entry<K,V> sublower(K key) {
1493 <            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1494 <                getLowerEntry(toKey) :  getLowerEntry(key);
1495 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1496 <                return null;
1497 <            return e;
1492 >        // Views
1493 >        transient NavigableMap<K,V> descendingMapView = null;
1494 >        transient EntrySetView entrySetView = null;
1495 >        transient KeySet<K> navigableKeySetView = null;
1496 >
1497 >        public final NavigableSet<K> navigableKeySet() {
1498 >            KeySet<K> nksv = navigableKeySetView;
1499 >            return (nksv != null) ? nksv :
1500 >                (navigableKeySetView = new TreeMap.KeySet(this));
1501          }
1502  
1503 <        public Map.Entry<K,V> lowerEntry(K key) {
1504 <            TreeMap.Entry<K,V> e = sublower(key);
1391 <            return e == null? null : new SnapshotEntry(e);
1503 >        public final Set<K> keySet() {
1504 >            return navigableKeySet();
1505          }
1506  
1507 <        public K lowerKey(K key) {
1508 <            TreeMap.Entry<K,V> e = sublower(key);
1396 <            return e == null? null : e.key;
1507 >        public NavigableSet<K> descendingKeySet() {
1508 >            return descendingMap().navigableKeySet();
1509          }
1510  
1511 <        private transient Set<Map.Entry<K,V>> entrySet = new EntrySetView();
1511 >        public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1512 >            return subMap(fromKey, true, toKey, false);
1513 >        }
1514  
1515 <        public Set<Map.Entry<K,V>> entrySet() {
1516 <            return entrySet;
1515 >        public final SortedMap<K,V> headMap(K toKey) {
1516 >            return headMap(toKey, false);
1517 >        }
1518 >
1519 >        public final SortedMap<K,V> tailMap(K fromKey) {
1520 >            return tailMap(fromKey, true);
1521          }
1522  
1523 <        private class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1523 >        // View classes
1524 >
1525 >        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1526              private transient int size = -1, sizeModCount;
1527  
1528              public int size() {
1529 <                if (size == -1 || sizeModCount != TreeMap.this.modCount) {
1530 <                    size = 0;  sizeModCount = TreeMap.this.modCount;
1529 >                if (fromStart && toEnd)
1530 >                    return m.size();
1531 >                if (size == -1 || sizeModCount != m.modCount) {
1532 >                    sizeModCount = m.modCount;
1533 >                    size = 0;
1534                      Iterator i = iterator();
1535                      while (i.hasNext()) {
1536                          size++;
# Line 1418 | Line 1541 | public class TreeMap<K,V>
1541              }
1542  
1543              public boolean isEmpty() {
1544 <                return !iterator().hasNext();
1544 >                TreeMap.Entry<K,V> n = absLowest();
1545 >                return n == null || tooHigh(n.key);
1546              }
1547  
1548              public boolean contains(Object o) {
# Line 1428 | Line 1552 | public class TreeMap<K,V>
1552                  K key = entry.getKey();
1553                  if (!inRange(key))
1554                      return false;
1555 <                TreeMap.Entry node = getEntry(key);
1555 >                TreeMap.Entry node = m.getEntry(key);
1556                  return node != null &&
1557 <                       valEquals(node.getValue(), entry.getValue());
1557 >                    valEquals(node.getValue(), entry.getValue());
1558              }
1559  
1560              public boolean remove(Object o) {
# Line 1440 | Line 1564 | public class TreeMap<K,V>
1564                  K key = entry.getKey();
1565                  if (!inRange(key))
1566                      return false;
1567 <                TreeMap.Entry<K,V> node = getEntry(key);
1567 >                TreeMap.Entry<K,V> node = m.getEntry(key);
1568                  if (node!=null && valEquals(node.getValue(),entry.getValue())){
1569 <                    deleteEntry(node);
1569 >                    m.deleteEntry(node);
1570                      return true;
1571                  }
1572                  return false;
1573              }
1450
1451            public Iterator<Map.Entry<K,V>> iterator() {
1452                return new SubMapEntryIterator(
1453                    (fromStart ? getFirstEntry() : getCeilingEntry(fromKey)),
1454                    (toEnd     ? null            : getCeilingEntry(toKey)));
1455            }
1574          }
1575  
1576 <        private transient Set<Map.Entry<K,V>> descendingEntrySetView = null;
1577 <        private transient Set<K> descendingKeySetView = null;
1578 <
1579 <        public Set<Map.Entry<K,V>> descendingEntrySet() {
1580 <            Set<Map.Entry<K,V>> es = descendingEntrySetView;
1581 <            return (es != null) ? es : (descendingEntrySetView = new DescendingEntrySetView());
1582 <        }
1576 >        /**
1577 >         * Iterators for SubMaps
1578 >         */
1579 >        abstract class SubMapIterator<T> implements Iterator<T> {
1580 >            TreeMap.Entry<K,V> lastReturned;
1581 >            TreeMap.Entry<K,V> next;
1582 >            final K fenceKey;
1583 >            int expectedModCount;
1584  
1585 <        public Set<K> descendingKeySet() {
1586 <            Set<K> ks = descendingKeySetView;
1587 <            return (ks != null) ? ks : (descendingKeySetView = new DescendingKeySetView());
1588 <        }
1585 >            SubMapIterator(TreeMap.Entry<K,V> first,
1586 >                           TreeMap.Entry<K,V> fence) {
1587 >                expectedModCount = m.modCount;
1588 >                lastReturned = null;
1589 >                next = first;
1590 >                fenceKey = fence == null ? null : fence.key;
1591 >            }
1592  
1593 <        private class DescendingEntrySetView extends EntrySetView {
1594 <            public Iterator<Map.Entry<K,V>> iterator() {
1473 <                return new DescendingSubMapEntryIterator
1474 <                    ((toEnd     ? getLastEntry()  : getLowerEntry(toKey)),
1475 <                     (fromStart ? null            : getLowerEntry(fromKey)));
1593 >            public final boolean hasNext() {
1594 >                return next != null && next.key != fenceKey;
1595              }
1477        }
1596  
1597 <        private class DescendingKeySetView extends AbstractSet<K> {
1598 <            public Iterator<K> iterator() {
1599 <                return new Iterator<K>() {
1600 <                    private Iterator<Entry<K,V>> i = descendingEntrySet().iterator();
1601 <                    
1602 <                    public boolean hasNext() { return i.hasNext(); }
1603 <                    public K next() { return i.next().getKey(); }
1604 <                    public void remove() { i.remove(); }
1487 <                };
1597 >            final TreeMap.Entry<K,V> nextEntry() {
1598 >                TreeMap.Entry<K,V> e = lastReturned = next;
1599 >                if (e == null || e.key == fenceKey)
1600 >                    throw new NoSuchElementException();
1601 >                if (m.modCount != expectedModCount)
1602 >                    throw new ConcurrentModificationException();
1603 >                next = successor(e);
1604 >                return e;
1605              }
1606 <            
1607 <            public int size() {
1608 <                return SubMap.this.size();
1606 >
1607 >            final TreeMap.Entry<K,V> prevEntry() {
1608 >                TreeMap.Entry<K,V> e = lastReturned = next;
1609 >                if (e == null || e.key == fenceKey)
1610 >                    throw new NoSuchElementException();
1611 >                if (m.modCount != expectedModCount)
1612 >                    throw new ConcurrentModificationException();
1613 >                next = predecessor(e);
1614 >                return e;
1615              }
1616 <            
1617 <            public boolean contains(Object k) {
1618 <                return SubMap.this.containsKey(k);
1616 >
1617 >            public void remove() {
1618 >                if (lastReturned == null)
1619 >                    throw new IllegalStateException();
1620 >                if (m.modCount != expectedModCount)
1621 >                    throw new ConcurrentModificationException();
1622 >                if (lastReturned.left != null && lastReturned.right != null)
1623 >                    next = lastReturned;
1624 >                m.deleteEntry(lastReturned);
1625 >                expectedModCount++;
1626 >                lastReturned = null;
1627              }
1628          }
1629  
1630 <
1631 <        public NavigableMap<K,V> subMap(K fromKey, K toKey) {
1632 <            if (!inRange2(fromKey))
1633 <                throw new IllegalArgumentException("fromKey out of range");
1634 <            if (!inRange2(toKey))
1635 <                throw new IllegalArgumentException("toKey out of range");
1636 <            return new SubMap(fromKey, toKey);
1630 >        final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1631 >            SubMapEntryIterator(TreeMap.Entry<K,V> first,
1632 >                                TreeMap.Entry<K,V> fence) {
1633 >                super(first, fence);
1634 >            }
1635 >            public Map.Entry<K,V> next() {
1636 >                return nextEntry();
1637 >            }
1638          }
1639  
1640 <        public NavigableMap<K,V> headMap(K toKey) {
1641 <            if (!inRange2(toKey))
1642 <                throw new IllegalArgumentException("toKey out of range");
1643 <            return new SubMap(fromStart, fromKey, false, toKey);
1640 >        final class SubMapKeyIterator extends SubMapIterator<K> {
1641 >            SubMapKeyIterator(TreeMap.Entry<K,V> first,
1642 >                              TreeMap.Entry<K,V> fence) {
1643 >                super(first, fence);
1644 >            }
1645 >            public K next() {
1646 >                return nextEntry().key;
1647 >            }
1648          }
1649  
1650 <        public NavigableMap<K,V> tailMap(K fromKey) {
1651 <            if (!inRange2(fromKey))
1652 <                throw new IllegalArgumentException("fromKey out of range");
1653 <            return new SubMap(false, fromKey, toEnd, toKey);
1654 <        }
1650 >        final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1651 >            DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
1652 >                                          TreeMap.Entry<K,V> fence) {
1653 >                super(last, fence);
1654 >            }
1655  
1656 <        private boolean inRange(K key) {
1657 <            return (fromStart || compare(key, fromKey) >= 0) &&
1658 <                   (toEnd     || compare(key, toKey)   <  0);
1656 >            public Map.Entry<K,V> next() {
1657 >                return prevEntry();
1658 >            }
1659          }
1660  
1661 <        // This form allows the high endpoint (as well as all legit keys)
1662 <        private boolean inRange2(K key) {
1663 <            return (fromStart || compare(key, fromKey) >= 0) &&
1664 <                   (toEnd     || compare(key, toKey)   <= 0);
1661 >        final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
1662 >            DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
1663 >                                        TreeMap.Entry<K,V> fence) {
1664 >                super(last, fence);
1665 >            }
1666 >            public K next() {
1667 >                return prevEntry().key;
1668 >            }
1669          }
1670      }
1671  
1672 <    /**
1673 <     * 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;
1672 >    static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1673 >        private static final long serialVersionUID = 912986545866124060L;
1674  
1675 <        PrivateEntryIterator(Entry<K,V> first) {
1676 <            next = first;
1675 >        AscendingSubMap(TreeMap<K,V> m,
1676 >                        boolean fromStart, K lo, boolean loInclusive,
1677 >                        boolean toEnd, K hi, boolean hiInclusive) {
1678 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1679          }
1680  
1681 <        public boolean hasNext() {
1682 <            return next != null;
1681 >        public Comparator<? super K> comparator() {
1682 >            return m.comparator();
1683          }
1684  
1685 <        Entry<K,V> nextEntry() {
1686 <            if (next == null)
1687 <                throw new NoSuchElementException();
1688 <            if (modCount != expectedModCount)
1689 <                throw new ConcurrentModificationException();
1690 <            lastReturned = next;
1691 <            next = successor(next);
1692 <            return lastReturned;
1685 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1686 >                                        K toKey, boolean toInclusive) {
1687 >            if (!inRange(fromKey, fromInclusive))
1688 >                throw new IllegalArgumentException("fromKey out of range");
1689 >            if (!inRange(toKey, toInclusive))
1690 >                throw new IllegalArgumentException("toKey out of range");
1691 >            return new AscendingSubMap(m,
1692 >                                       false, fromKey, fromInclusive,
1693 >                                       false, toKey,   toInclusive);
1694          }
1695  
1696 <        public void remove() {
1697 <            if (lastReturned == null)
1698 <                throw new IllegalStateException();
1699 <            if (modCount != expectedModCount)
1700 <                throw new ConcurrentModificationException();
1701 <            if (lastReturned.left != null && lastReturned.right != null)
1564 <                next = lastReturned;
1565 <            deleteEntry(lastReturned);
1566 <            expectedModCount++;
1567 <            lastReturned = null;
1696 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1697 >            if (!inClosedRange(toKey))
1698 >                throw new IllegalArgumentException("toKey out of range");
1699 >            return new AscendingSubMap(m,
1700 >                                       fromStart, lo,    loInclusive,
1701 >                                       false,     toKey, inclusive);
1702          }
1569    }
1703  
1704 <    class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1705 <        EntryIterator(Entry<K,V> first) {
1706 <            super(first);
1704 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1705 >            if (!inRange(fromKey, inclusive))
1706 >                throw new IllegalArgumentException("fromKey out of range");
1707 >            return new AscendingSubMap(m,
1708 >                                       false, fromKey, inclusive,
1709 >                                       toEnd, hi,      hiInclusive);
1710          }
1711  
1712 <        public Map.Entry<K,V> next() {
1713 <            return nextEntry();
1712 >        public NavigableMap<K,V> descendingMap() {
1713 >            NavigableMap<K,V> mv = descendingMapView;
1714 >            return (mv != null) ? mv :
1715 >                (descendingMapView =
1716 >                 new DescendingSubMap(m,
1717 >                                      fromStart, lo, loInclusive,
1718 >                                      toEnd,     hi, hiInclusive));
1719          }
1579    }
1720  
1721 <    class KeyIterator extends PrivateEntryIterator<K> {
1722 <        KeyIterator(Entry<K,V> first) {
1583 <            super(first);
1721 >        Iterator<K> keyIterator() {
1722 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1723          }
1585        public K next() {
1586            return nextEntry().key;
1587        }
1588    }
1724  
1725 <    class ValueIterator extends PrivateEntryIterator<V> {
1726 <        ValueIterator(Entry<K,V> first) {
1592 <            super(first);
1593 <        }
1594 <        public V next() {
1595 <            return nextEntry().value;
1725 >        Iterator<K> descendingKeyIterator() {
1726 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1727          }
1597    }
1728  
1729 <    class SubMapEntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1730 <        private final K firstExcludedKey;
1731 <
1732 <        SubMapEntryIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1603 <            super(first);
1604 <            firstExcludedKey = (firstExcluded == null
1605 <                                ? null
1606 <                                : firstExcluded.key);
1729 >        final class AscendingEntrySetView extends EntrySetView {
1730 >            public Iterator<Map.Entry<K,V>> iterator() {
1731 >                return new SubMapEntryIterator(absLowest(), absHighFence());
1732 >            }
1733          }
1734  
1735 <        public boolean hasNext() {
1736 <            return next != null && next.key != firstExcludedKey;
1735 >        public Set<Map.Entry<K,V>> entrySet() {
1736 >            EntrySetView es = entrySetView;
1737 >            return (es != null) ? es : new AscendingEntrySetView();
1738          }
1739  
1740 <        public Map.Entry<K,V> next() {
1741 <            if (next == null || next.key == firstExcludedKey)
1742 <                throw new NoSuchElementException();
1743 <            return nextEntry();
1744 <        }
1740 >        TreeMap.Entry<K,V> subLowest()       { return absLowest(); }
1741 >        TreeMap.Entry<K,V> subHighest()      { return absHighest(); }
1742 >        TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); }
1743 >        TreeMap.Entry<K,V> subHigher(K key)  { return absHigher(key); }
1744 >        TreeMap.Entry<K,V> subFloor(K key)   { return absFloor(key); }
1745 >        TreeMap.Entry<K,V> subLower(K key)   { return absLower(key); }
1746      }
1747  
1748 <
1749 <    /**
1750 <     * Base for Descending Iterators.
1751 <     */
1752 <    abstract class DescendingPrivateEntryIterator<T> extends PrivateEntryIterator<T> {
1753 <        DescendingPrivateEntryIterator(Entry<K,V> first) {
1626 <            super(first);
1748 >    static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
1749 >        private static final long serialVersionUID = 912986545866120460L;
1750 >        DescendingSubMap(TreeMap<K,V> m,
1751 >                        boolean fromStart, K lo, boolean loInclusive,
1752 >                        boolean toEnd, K hi, boolean hiInclusive) {
1753 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1754          }
1755  
1756 <        Entry<K,V> nextEntry() {
1757 <            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 <    }
1756 >        private final Comparator<? super K> reverseComparator =
1757 >            Collections.reverseOrder(m.comparator);
1758  
1759 <    class DescendingEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1760 <        DescendingEntryIterator(Entry<K,V> first) {
1642 <            super(first);
1759 >        public Comparator<? super K> comparator() {
1760 >            return reverseComparator;
1761          }
1762 <        public Map.Entry<K,V> next() {
1763 <            return nextEntry();
1762 >
1763 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1764 >                                        K toKey, boolean toInclusive) {
1765 >            if (!inRange(fromKey, fromInclusive))
1766 >                throw new IllegalArgumentException("fromKey out of range");
1767 >            if (!inRange(toKey, toInclusive))
1768 >                throw new IllegalArgumentException("toKey out of range");
1769 >            return new DescendingSubMap(m,
1770 >                                        false, toKey,   toInclusive,
1771 >                                        false, fromKey, fromInclusive);
1772          }
1647    }
1773  
1774 <    class DescendingKeyIterator extends DescendingPrivateEntryIterator<K> {
1775 <        DescendingKeyIterator(Entry<K,V> first) {
1776 <            super(first);
1774 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1775 >            if (!inRange(toKey, inclusive))
1776 >                throw new IllegalArgumentException("toKey out of range");
1777 >            return new DescendingSubMap(m,
1778 >                                        false, toKey, inclusive,
1779 >                                        toEnd, hi,    hiInclusive);
1780          }
1781 <        public K next() {
1782 <            return nextEntry().key;
1781 >
1782 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1783 >            if (!inRange(fromKey, inclusive))
1784 >                throw new IllegalArgumentException("fromKey out of range");
1785 >            return new DescendingSubMap(m,
1786 >                                        fromStart, lo, loInclusive,
1787 >                                        false, fromKey, inclusive);
1788          }
1656    }
1789  
1790 +        public NavigableMap<K,V> descendingMap() {
1791 +            NavigableMap<K,V> mv = descendingMapView;
1792 +            return (mv != null) ? mv :
1793 +                (descendingMapView =
1794 +                 new AscendingSubMap(m,
1795 +                                     fromStart, lo, loInclusive,
1796 +                                     toEnd,     hi, hiInclusive));
1797 +        }
1798  
1799 <    class DescendingSubMapEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1800 <        private final K lastExcludedKey;
1799 >        Iterator<K> keyIterator() {
1800 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1801 >        }
1802  
1803 <        DescendingSubMapEntryIterator(Entry<K,V> last, Entry<K,V> lastExcluded) {
1804 <            super(last);
1664 <            lastExcludedKey = (lastExcluded == null
1665 <                                ? null
1666 <                                : lastExcluded.key);
1803 >        Iterator<K> descendingKeyIterator() {
1804 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1805          }
1806  
1807 <        public boolean hasNext() {
1808 <            return next != null && next.key != lastExcludedKey;
1807 >        final class DescendingEntrySetView extends EntrySetView {
1808 >            public Iterator<Map.Entry<K,V>> iterator() {
1809 >                return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
1810 >            }
1811          }
1812  
1813 <        public Map.Entry<K,V> next() {
1814 <            if (next == null || next.key == lastExcludedKey)
1815 <                throw new NoSuchElementException();
1676 <            return nextEntry();
1813 >        public Set<Map.Entry<K,V>> entrySet() {
1814 >            EntrySetView es = entrySetView;
1815 >            return (es != null) ? es : new DescendingEntrySetView();
1816          }
1817  
1818 +        TreeMap.Entry<K,V> subLowest()       { return absHighest(); }
1819 +        TreeMap.Entry<K,V> subHighest()      { return absLowest(); }
1820 +        TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
1821 +        TreeMap.Entry<K,V> subHigher(K key)  { return absLower(key); }
1822 +        TreeMap.Entry<K,V> subFloor(K key)   { return absCeiling(key); }
1823 +        TreeMap.Entry<K,V> subLower(K key)   { return absHigher(key); }
1824      }
1825  
1681
1826      /**
1827 <     * Compares two keys using the correct comparison method for this TreeMap.
1827 >     * This class exists solely for the sake of serialization
1828 >     * compatibility with previous releases of TreeMap that did not
1829 >     * support NavigableMap.  It translates an old-version SubMap into
1830 >     * a new-version AscendingSubMap. This class is never otherwise
1831 >     * used.
1832       */
1833 <    private int compare(K k1, K k2) {
1834 <        return (comparator==null ? ((Comparable</*-*/K>)k1).compareTo(k2)
1835 <                                 : comparator.compare((K)k1, (K)k2));
1833 >    private class SubMap extends AbstractMap<K,V>
1834 >        implements SortedMap<K,V>, java.io.Serializable {
1835 >        private static final long serialVersionUID = -6520786458950516097L;
1836 >        private boolean fromStart = false, toEnd = false;
1837 >        private K fromKey, toKey;
1838 >        private Object readResolve() {
1839 >            return new AscendingSubMap(TreeMap.this,
1840 >                                       fromStart, fromKey, true,
1841 >                                       toEnd, toKey, false);
1842 >        }
1843 >        public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
1844 >        public K lastKey() { throw new InternalError(); }
1845 >        public K firstKey() { throw new InternalError(); }
1846 >        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
1847 >        public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
1848 >        public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
1849 >        public Comparator<? super K> comparator() { throw new InternalError(); }
1850      }
1851  
1852 <    /**
1853 <     * 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 <    }
1852 >
1853 >    // Red-black mechanics
1854  
1855      private static final boolean RED   = false;
1856      private static final boolean BLACK = true;
# Line 1703 | Line 1860 | public class TreeMap<K,V>
1860       * user (see Map.Entry).
1861       */
1862  
1863 <    static class Entry<K,V> implements Map.Entry<K,V> {
1863 >    static final class Entry<K,V> implements Map.Entry<K,V> {
1864          K key;
1865          V value;
1866          Entry<K,V> left = null;
# Line 1724 | Line 1881 | public class TreeMap<K,V>
1881          /**
1882           * Returns the key.
1883           *
1884 <         * @return the key.
1884 >         * @return the key
1885           */
1886          public K getKey() {
1887              return key;
# Line 1733 | Line 1890 | public class TreeMap<K,V>
1890          /**
1891           * Returns the value associated with the key.
1892           *
1893 <         * @return the value associated with the key.
1893 >         * @return the value associated with the key
1894           */
1895          public V getValue() {
1896              return value;
# Line 1744 | Line 1901 | public class TreeMap<K,V>
1901           * value.
1902           *
1903           * @return the value associated with the key before this method was
1904 <         *           called.
1904 >         *         called
1905           */
1906          public V setValue(V value) {
1907              V oldValue = this.value;
# Line 1775 | Line 1932 | public class TreeMap<K,V>
1932       * Returns the first Entry in the TreeMap (according to the TreeMap's
1933       * key-sort function).  Returns null if the TreeMap is empty.
1934       */
1935 <    private Entry<K,V> getFirstEntry() {
1935 >    final Entry<K,V> getFirstEntry() {
1936          Entry<K,V> p = root;
1937          if (p != null)
1938              while (p.left != null)
# Line 1787 | Line 1944 | public class TreeMap<K,V>
1944       * Returns the last Entry in the TreeMap (according to the TreeMap's
1945       * key-sort function).  Returns null if the TreeMap is empty.
1946       */
1947 <    private Entry<K,V> getLastEntry() {
1947 >    final Entry<K,V> getLastEntry() {
1948          Entry<K,V> p = root;
1949          if (p != null)
1950              while (p.right != null)
# Line 1798 | Line 1955 | public class TreeMap<K,V>
1955      /**
1956       * Returns the successor of the specified Entry, or null if no such.
1957       */
1958 <    private Entry<K,V> successor(Entry<K,V> t) {
1958 >    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
1959          if (t == null)
1960              return null;
1961          else if (t.right != null) {
# Line 1820 | Line 1977 | public class TreeMap<K,V>
1977      /**
1978       * Returns the predecessor of the specified Entry, or null if no such.
1979       */
1980 <    private Entry<K,V> predecessor(Entry<K,V> t) {
1980 >    static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {
1981          if (t == null)
1982              return null;
1983          else if (t.left != null) {
# Line 1870 | Line 2027 | public class TreeMap<K,V>
2027          return (p == null) ? null: p.right;
2028      }
2029  
2030 <    /** From CLR **/
2030 >    /** From CLR */
2031      private void rotateLeft(Entry<K,V> p) {
2032          Entry<K,V> r = p.right;
2033          p.right = r.left;
# Line 1887 | Line 2044 | public class TreeMap<K,V>
2044          p.parent = r;
2045      }
2046  
2047 <    /** From CLR **/
2047 >    /** From CLR */
2048      private void rotateRight(Entry<K,V> p) {
2049          Entry<K,V> l = p.left;
2050          p.left = l.right;
# Line 1903 | Line 2060 | public class TreeMap<K,V>
2060      }
2061  
2062  
2063 <    /** From CLR **/
2063 >    /** From CLR */
2064      private void fixAfterInsertion(Entry<K,V> x) {
2065          x.color = RED;
2066  
# Line 1937 | Line 2094 | public class TreeMap<K,V>
2094                          x = parentOf(x);
2095                          rotateRight(x);
2096                      }
2097 <                    setColor(parentOf(x),  BLACK);
2097 >                    setColor(parentOf(x), BLACK);
2098                      setColor(parentOf(parentOf(x)), RED);
2099                      if (parentOf(parentOf(x)) != null)
2100                          rotateLeft(parentOf(parentOf(x)));
# Line 1952 | Line 2109 | public class TreeMap<K,V>
2109       */
2110  
2111      private void deleteEntry(Entry<K,V> p) {
2112 <        decrementSize();
2112 >        modCount++;
2113 >        size--;
2114  
2115          // If strictly internal, copy successor's element to p and then make p
2116          // point to successor.
# Line 1998 | Line 2156 | public class TreeMap<K,V>
2156          }
2157      }
2158  
2159 <    /** From CLR **/
2159 >    /** From CLR */
2160      private void fixAfterDeletion(Entry<K,V> x) {
2161          while (x != root && colorOf(x) == BLACK) {
2162              if (x == leftOf(parentOf(x))) {
# Line 2013 | Line 2171 | public class TreeMap<K,V>
2171  
2172                  if (colorOf(leftOf(sib))  == BLACK &&
2173                      colorOf(rightOf(sib)) == BLACK) {
2174 <                    setColor(sib,  RED);
2174 >                    setColor(sib, RED);
2175                      x = parentOf(x);
2176                  } else {
2177                      if (colorOf(rightOf(sib)) == BLACK) {
# Line 2040 | Line 2198 | public class TreeMap<K,V>
2198  
2199                  if (colorOf(rightOf(sib)) == BLACK &&
2200                      colorOf(leftOf(sib)) == BLACK) {
2201 <                    setColor(sib,  RED);
2201 >                    setColor(sib, RED);
2202                      x = parentOf(x);
2203                  } else {
2204                      if (colorOf(leftOf(sib)) == BLACK) {
# Line 2091 | Line 2249 | public class TreeMap<K,V>
2249          }
2250      }
2251  
2094
2095
2252      /**
2253       * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e.,
2254       * deserialize it).
# Line 2108 | Line 2264 | public class TreeMap<K,V>
2264          buildFromSorted(size, null, s, null);
2265      }
2266  
2267 <    /** Intended to be called only from TreeSet.readObject **/
2267 >    /** Intended to be called only from TreeSet.readObject */
2268      void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2269          throws java.io.IOException, ClassNotFoundException {
2270          buildFromSorted(size, null, s, defaultVal);
2271      }
2272  
2273 <    /** Intended to be called only from TreeSet.addAll **/
2274 <    void addAllForTreeSet(SortedSet<Map.Entry<K,V>> set, V defaultVal) {
2273 >    /** Intended to be called only from TreeSet.addAll */
2274 >    void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2275          try {
2276              buildFromSorted(set.size(), set.iterator(), null, defaultVal);
2277          } catch (java.io.IOException cannotHappen) {
# Line 2140 | Line 2296 | public class TreeMap<K,V>
2296       * to calling this method.
2297       *
2298       * @param size the number of keys (or key-value pairs) to be read from
2299 <     *        the iterator or stream.
2299 >     *        the iterator or stream
2300       * @param it If non-null, new entries are created from entries
2301       *        or keys read from this iterator.
2302       * @param str If non-null, new entries are created from keys and
# Line 2154 | Line 2310 | public class TreeMap<K,V>
2310       * @throws ClassNotFoundException propagated from readObject.
2311       *         This cannot occur if str is null.
2312       */
2313 <    private
2314 <    void buildFromSorted(int size, Iterator it,
2315 <                         java.io.ObjectInputStream str,
2160 <                         V defaultVal)
2313 >    private void buildFromSorted(int size, Iterator it,
2314 >                                 java.io.ObjectInputStream str,
2315 >                                 V defaultVal)
2316          throws  java.io.IOException, ClassNotFoundException {
2317          this.size = size;
2318 <        root =
2319 <            buildFromSorted(0, 0, size-1, computeRedLevel(size),
2165 <                            it, str, defaultVal);
2318 >        root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
2319 >                               it, str, defaultVal);
2320      }
2321  
2322      /**
2323       * Recursive "helper method" that does the real work of the
2324 <     * of the previous method.  Identically named parameters have
2324 >     * previous method.  Identically named parameters have
2325       * identical definitions.  Additional parameters are documented below.
2326       * It is assumed that the comparator and size fields of the TreeMap are
2327       * already set prior to calling this method.  (It ignores both fields.)
# Line 2175 | Line 2329 | public class TreeMap<K,V>
2329       * @param level the current level of tree. Initial call should be 0.
2330       * @param lo the first element index of this subtree. Initial should be 0.
2331       * @param hi the last element index of this subtree.  Initial should be
2332 <     *              size-1.
2332 >     *        size-1.
2333       * @param redLevel the level at which nodes should be red.
2334       *        Must be equal to computeRedLevel for tree of this size.
2335       */
# Line 2259 | Line 2413 | public class TreeMap<K,V>
2413              level++;
2414          return level;
2415      }
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
2416   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines