ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.42
Committed: Tue Jan 30 03:54:29 2007 UTC (17 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.41: +8 -2 lines
Log Message:
6467933: (coll) TreeMap head/tailMap() methods handle null keys incorrectly

File Contents

# User Rev Content
1 dl 1.1 /*
2     * %W% %E%
3     *
4 jsr166 1.41 * Copyright 2007 Sun Microsystems, Inc. All rights reserved.
5 dl 1.1 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6     */
7    
8 dl 1.8 package java.util;
9 dl 1.1
10     /**
11 jsr166 1.14 * 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 dl 1.1 *
16 jsr166 1.14 * <p>This implementation provides guaranteed log(n) time cost for the
17 dl 1.1 * <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 jsr166 1.14 * Rivest's <I>Introduction to Algorithms</I>.
20 dl 1.1 *
21 jsr166 1.14 * <p>Note that the ordering maintained by a sorted map (whether or not an
22 dl 1.1 * 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
25     * <i>consistent with equals</i>.) This is so because the <tt>Map</tt>
26     * interface is defined in terms of the equals operation, but a map performs
27     * all key comparisons using its <tt>compareTo</tt> (or <tt>compare</tt>)
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 jsr166 1.14 * just fails to obey the general contract of the <tt>Map</tt> interface.
32 dl 1.1 *
33 jsr166 1.23 * <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 dl 1.1 *
47 jsr166 1.14 * <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 dl 1.1 * <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 jsr166 1.14 * <tt>remove</tt> method, the iterator will throw a {@link
52     * ConcurrentModificationException}. Thus, in the face of concurrent
53 dl 1.1 * modification, the iterator fails quickly and cleanly, rather than risking
54 jsr166 1.14 * arbitrary, non-deterministic behavior at an undetermined time in the future.
55 dl 1.1 *
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
58     * presence of unsynchronized concurrent modification. Fail-fast iterators
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 dl 1.5 * should be used only to detect bugs.</i>
63 dl 1.1 *
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
66     * produced. They do <em>not</em> support the <tt>Entry.setValue</tt>
67     * method. (Note however that it is possible to change mappings in the
68     * associated map using <tt>put</tt>.)
69     *
70     * <p>This class is a member of the
71 jsr166 1.35 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
72 dl 1.1 * Java Collections Framework</a>.
73     *
74 jsr166 1.14 * @param <K> the type of keys maintained by this map
75     * @param <V> the type of mapped values
76     *
77 dl 1.1 * @author Josh Bloch and Doug Lea
78     * @version %I%, %G%
79     * @see Map
80     * @see HashMap
81     * @see Hashtable
82     * @see Comparable
83     * @see Comparator
84     * @see Collection
85     * @since 1.2
86     */
87    
88     public class TreeMap<K,V>
89     extends AbstractMap<K,V>
90     implements NavigableMap<K,V>, Cloneable, java.io.Serializable
91     {
92     /**
93 jsr166 1.14 * The comparator used to maintain order in this tree map, or
94     * null if it uses the natural ordering of its keys.
95 dl 1.1 *
96     * @serial
97     */
98 dl 1.31 private final Comparator<? super K> comparator;
99 dl 1.1
100     private transient Entry<K,V> root = null;
101    
102     /**
103     * The number of entries in the tree
104     */
105     private transient int size = 0;
106    
107     /**
108     * The number of structural modifications to the tree.
109     */
110     private transient int modCount = 0;
111    
112     /**
113 jsr166 1.14 * 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 dl 1.1 */
124     public TreeMap() {
125 dl 1.31 comparator = null;
126 dl 1.1 }
127    
128     /**
129 jsr166 1.14 * 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 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 dl 1.1 }
145    
146     /**
147 jsr166 1.14 * 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 dl 1.1 */
160     public TreeMap(Map<? extends K, ? extends V> m) {
161 dl 1.31 comparator = null;
162 dl 1.1 putAll(m);
163     }
164    
165     /**
166 jsr166 1.14 * 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 dl 1.1 *
170     * @param m the sorted map whose mappings are to be placed in this map,
171 jsr166 1.14 * and whose comparator is to be used to sort this map
172     * @throws NullPointerException if the specified map is null
173 dl 1.1 */
174     public TreeMap(SortedMap<K, ? extends V> m) {
175     comparator = m.comparator();
176     try {
177     buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
178     } catch (java.io.IOException cannotHappen) {
179     } catch (ClassNotFoundException cannotHappen) {
180     }
181     }
182    
183    
184     // Query Operations
185    
186     /**
187     * Returns the number of key-value mappings in this map.
188     *
189 jsr166 1.14 * @return the number of key-value mappings in this map
190 dl 1.1 */
191     public int size() {
192     return size;
193     }
194    
195     /**
196     * Returns <tt>true</tt> if this map contains a mapping for the specified
197     * key.
198     *
199 jsr166 1.14 * @param key key whose presence in this map is to be tested
200 dl 1.1 * @return <tt>true</tt> if this map contains a mapping for the
201 jsr166 1.14 * 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 dl 1.1 */
208     public boolean containsKey(Object key) {
209     return getEntry(key) != null;
210     }
211    
212     /**
213     * Returns <tt>true</tt> if this map maps one or more keys to the
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 jsr166 1.19 * operation will probably require time linear in the map size for
218     * most implementations.
219 dl 1.1 *
220 jsr166 1.14 * @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 dl 1.1 * @since 1.2
224     */
225     public boolean containsValue(Object value) {
226 dl 1.34 for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
227     if (valEquals(value, e.value))
228     return true;
229     return false;
230 dl 1.1 }
231    
232     /**
233 jsr166 1.24 * Returns the value to which the specified key is mapped,
234     * or {@code null} if this map contains no mapping for the key.
235     *
236     * <p>More formally, if this map contains a mapping from a key
237     * {@code k} to a value {@code v} such that {@code key} compares
238     * equal to {@code k} according to the map's ordering, then this
239     * method returns {@code v}; otherwise it returns {@code null}.
240     * (There can be at most one such mapping.)
241     *
242     * <p>A return value of {@code null} does not <i>necessarily</i>
243     * indicate that the map contains no mapping for the key; it's also
244     * possible that the map explicitly maps the key to {@code null}.
245     * The {@link #containsKey containsKey} operation may be used to
246     * distinguish these two cases.
247     *
248 jsr166 1.14 * @throws ClassCastException if the specified key cannot be compared
249     * with the keys currently in the map
250     * @throws NullPointerException if the specified key is null
251     * and this map uses natural ordering, or its comparator
252     * does not permit null keys
253 dl 1.1 */
254     public V get(Object key) {
255     Entry<K,V> p = getEntry(key);
256     return (p==null ? null : p.value);
257     }
258    
259     public Comparator<? super K> comparator() {
260     return comparator;
261     }
262    
263     /**
264 jsr166 1.14 * @throws NoSuchElementException {@inheritDoc}
265 dl 1.1 */
266     public K firstKey() {
267     return key(getFirstEntry());
268     }
269    
270     /**
271 jsr166 1.14 * @throws NoSuchElementException {@inheritDoc}
272 dl 1.1 */
273     public K lastKey() {
274     return key(getLastEntry());
275     }
276    
277     /**
278 jsr166 1.14 * Copies all of the mappings from the specified map to this map.
279     * These mappings replace any mappings that this map had for any
280     * of the keys currently in the specified map.
281     *
282     * @param map mappings to be stored in this map
283     * @throws ClassCastException if the class of a key or value in
284     * the specified map prevents it from being stored in this map
285     * @throws NullPointerException if the specified map is null or
286     * the specified map contains a null key and this map does not
287     * permit null keys
288 dl 1.1 */
289     public void putAll(Map<? extends K, ? extends V> map) {
290     int mapSize = map.size();
291     if (size==0 && mapSize!=0 && map instanceof SortedMap) {
292     Comparator c = ((SortedMap)map).comparator();
293     if (c == comparator || (c != null && c.equals(comparator))) {
294     ++modCount;
295     try {
296     buildFromSorted(mapSize, map.entrySet().iterator(),
297     null, null);
298     } catch (java.io.IOException cannotHappen) {
299     } catch (ClassNotFoundException cannotHappen) {
300     }
301     return;
302     }
303     }
304     super.putAll(map);
305     }
306    
307     /**
308     * Returns this map's entry for the given key, or <tt>null</tt> if the map
309     * does not contain an entry for the key.
310     *
311     * @return this map's entry for the given key, or <tt>null</tt> if the map
312 jsr166 1.14 * does not contain an entry for the key
313     * @throws ClassCastException if the specified key cannot be compared
314     * with the keys currently in the map
315     * @throws NullPointerException if the specified key is null
316     * and this map uses natural ordering, or its comparator
317     * does not permit null keys
318 dl 1.1 */
319 dl 1.29 final Entry<K,V> getEntry(Object key) {
320 dl 1.1 // Offload comparator-based version for sake of performance
321     if (comparator != null)
322     return getEntryUsingComparator(key);
323 dl 1.28 if (key == null)
324     throw new NullPointerException();
325 jsr166 1.12 Comparable<? super K> k = (Comparable<? super K>) key;
326 dl 1.1 Entry<K,V> p = root;
327     while (p != null) {
328     int cmp = k.compareTo(p.key);
329     if (cmp < 0)
330     p = p.left;
331     else if (cmp > 0)
332     p = p.right;
333     else
334     return p;
335     }
336     return null;
337     }
338    
339     /**
340     * Version of getEntry using comparator. Split off from getEntry
341     * for performance. (This is not worth doing for most methods,
342     * that are less dependent on comparator performance, but is
343 dl 1.34 * worthwhile here.)
344 dl 1.1 */
345 dl 1.29 final Entry<K,V> getEntryUsingComparator(Object key) {
346 dl 1.1 K k = (K) key;
347     Comparator<? super K> cpr = comparator;
348 dl 1.34 if (cpr != null) {
349     Entry<K,V> p = root;
350     while (p != null) {
351     int cmp = cpr.compare(k, p.key);
352     if (cmp < 0)
353     p = p.left;
354     else if (cmp > 0)
355     p = p.right;
356     else
357     return p;
358     }
359 dl 1.1 }
360     return null;
361     }
362    
363     /**
364     * Gets the entry corresponding to the specified key; if no such entry
365     * exists, returns the entry for the least key greater than the specified
366     * key; if no such entry exists (i.e., the greatest key in the Tree is less
367     * than the specified key), returns <tt>null</tt>.
368     */
369 dl 1.29 final Entry<K,V> getCeilingEntry(K key) {
370 dl 1.1 Entry<K,V> p = root;
371 dl 1.31 while (p != null) {
372 dl 1.1 int cmp = compare(key, p.key);
373     if (cmp < 0) {
374     if (p.left != null)
375     p = p.left;
376     else
377     return p;
378     } else if (cmp > 0) {
379     if (p.right != null) {
380     p = p.right;
381     } else {
382     Entry<K,V> parent = p.parent;
383     Entry<K,V> ch = p;
384     while (parent != null && ch == parent.right) {
385     ch = parent;
386     parent = parent.parent;
387     }
388     return parent;
389     }
390     } else
391     return p;
392     }
393 dl 1.31 return null;
394 dl 1.1 }
395    
396     /**
397     * Gets the entry corresponding to the specified key; if no such entry
398     * exists, returns the entry for the greatest key less than the specified
399     * key; if no such entry exists, returns <tt>null</tt>.
400     */
401 dl 1.29 final Entry<K,V> getFloorEntry(K key) {
402 dl 1.1 Entry<K,V> p = root;
403 dl 1.31 while (p != null) {
404 dl 1.1 int cmp = compare(key, p.key);
405     if (cmp > 0) {
406     if (p.right != null)
407     p = p.right;
408     else
409     return p;
410     } else if (cmp < 0) {
411     if (p.left != null) {
412     p = p.left;
413     } else {
414     Entry<K,V> parent = p.parent;
415     Entry<K,V> ch = p;
416     while (parent != null && ch == parent.left) {
417     ch = parent;
418     parent = parent.parent;
419     }
420     return parent;
421     }
422     } else
423     return p;
424    
425     }
426 dl 1.31 return null;
427 dl 1.1 }
428    
429     /**
430     * Gets the entry for the least key greater than the specified
431     * key; if no such entry exists, returns the entry for the least
432     * key greater than the specified key; if no such entry exists
433     * returns <tt>null</tt>.
434     */
435 dl 1.29 final Entry<K,V> getHigherEntry(K key) {
436 dl 1.1 Entry<K,V> p = root;
437 dl 1.31 while (p != null) {
438 dl 1.1 int cmp = compare(key, p.key);
439     if (cmp < 0) {
440     if (p.left != null)
441     p = p.left;
442     else
443     return p;
444     } else {
445     if (p.right != null) {
446     p = p.right;
447     } else {
448     Entry<K,V> parent = p.parent;
449     Entry<K,V> ch = p;
450     while (parent != null && ch == parent.right) {
451     ch = parent;
452     parent = parent.parent;
453     }
454     return parent;
455     }
456     }
457     }
458 dl 1.31 return null;
459 dl 1.1 }
460    
461     /**
462     * Returns the entry for the greatest key less than the specified key; if
463     * no such entry exists (i.e., the least key in the Tree is greater than
464     * the specified key), returns <tt>null</tt>.
465     */
466 dl 1.29 final Entry<K,V> getLowerEntry(K key) {
467 dl 1.1 Entry<K,V> p = root;
468 dl 1.31 while (p != null) {
469 dl 1.1 int cmp = compare(key, p.key);
470     if (cmp > 0) {
471     if (p.right != null)
472     p = p.right;
473     else
474     return p;
475     } else {
476     if (p.left != null) {
477     p = p.left;
478     } else {
479     Entry<K,V> parent = p.parent;
480     Entry<K,V> ch = p;
481     while (parent != null && ch == parent.left) {
482     ch = parent;
483     parent = parent.parent;
484     }
485     return parent;
486     }
487     }
488     }
489 dl 1.31 return null;
490 dl 1.1 }
491    
492     /**
493     * Associates the specified value with the specified key in this map.
494 jsr166 1.20 * If the map previously contained a mapping for the key, the old
495 dl 1.1 * value is replaced.
496     *
497 jsr166 1.14 * @param key key with which the specified value is to be associated
498     * @param value value to be associated with the specified key
499 dl 1.1 *
500 jsr166 1.14 * @return the previous value associated with <tt>key</tt>, or
501     * <tt>null</tt> if there was no mapping for <tt>key</tt>.
502     * (A <tt>null</tt> return can also indicate that the map
503     * previously associated <tt>null</tt> with <tt>key</tt>.)
504     * @throws ClassCastException if the specified key cannot be compared
505     * with the keys currently in the map
506     * @throws NullPointerException if the specified key is null
507     * and this map uses natural ordering, or its comparator
508     * does not permit null keys
509 dl 1.1 */
510     public V put(K key, V value) {
511     Entry<K,V> t = root;
512 dl 1.34 if (t == null) {
513 jsr166 1.35 // TBD:
514     // 5045147: (coll) Adding null to an empty TreeSet should
515     // throw NullPointerException
516     //
517     // compare(key, key); // type check
518 dl 1.34 root = new Entry<K,V>(key, value, null);
519     size = 1;
520     modCount++;
521     return null;
522 dl 1.8 }
523 dl 1.34 int cmp;
524     Entry<K,V> parent;
525     // split comparator and comparable paths
526     Comparator<? super K> cpr = comparator;
527     if (cpr != null) {
528     do {
529     parent = t;
530     cmp = cpr.compare(key, t.key);
531     if (cmp < 0)
532     t = t.left;
533     else if (cmp > 0)
534     t = t.right;
535     else
536     return t.setValue(value);
537     } while (t != null);
538 dl 1.33 }
539 dl 1.34 else {
540     if (key == null)
541     throw new NullPointerException();
542     Comparable<? super K> k = (Comparable<? super K>) key;
543     do {
544     parent = t;
545     cmp = k.compareTo(t.key);
546     if (cmp < 0)
547     t = t.left;
548     else if (cmp > 0)
549     t = t.right;
550     else
551     return t.setValue(value);
552     } while (t != null);
553 dl 1.1 }
554 dl 1.33 Entry<K,V> e = new Entry<K,V>(key, value, parent);
555 dl 1.34 if (cmp < 0)
556     parent.left = e;
557     else
558     parent.right = e;
559     fixAfterInsertion(e);
560 dl 1.33 size++;
561     modCount++;
562 dl 1.31 return null;
563 dl 1.1 }
564    
565     /**
566     * Removes the mapping for this key from this TreeMap if present.
567     *
568     * @param key key for which mapping should be removed
569 jsr166 1.14 * @return the previous value associated with <tt>key</tt>, or
570     * <tt>null</tt> if there was no mapping for <tt>key</tt>.
571     * (A <tt>null</tt> return can also indicate that the map
572     * previously associated <tt>null</tt> with <tt>key</tt>.)
573     * @throws ClassCastException if the specified key cannot be compared
574     * with the keys currently in the map
575     * @throws NullPointerException if the specified key is null
576     * and this map uses natural ordering, or its comparator
577     * does not permit null keys
578 dl 1.1 */
579     public V remove(Object key) {
580     Entry<K,V> p = getEntry(key);
581     if (p == null)
582     return null;
583    
584     V oldValue = p.value;
585     deleteEntry(p);
586     return oldValue;
587     }
588    
589     /**
590 jsr166 1.14 * Removes all of the mappings from this map.
591     * The map will be empty after this call returns.
592 dl 1.1 */
593     public void clear() {
594     modCount++;
595     size = 0;
596     root = null;
597     }
598    
599     /**
600     * Returns a shallow copy of this <tt>TreeMap</tt> instance. (The keys and
601     * values themselves are not cloned.)
602     *
603 jsr166 1.14 * @return a shallow copy of this map
604 dl 1.1 */
605     public Object clone() {
606     TreeMap<K,V> clone = null;
607     try {
608     clone = (TreeMap<K,V>) super.clone();
609     } catch (CloneNotSupportedException e) {
610     throw new InternalError();
611     }
612    
613     // Put clone into "virgin" state (except for comparator)
614     clone.root = null;
615     clone.size = 0;
616     clone.modCount = 0;
617     clone.entrySet = null;
618 dl 1.28 clone.navigableKeySet = null;
619     clone.descendingMap = null;
620 dl 1.1
621     // Initialize clone with our mappings
622     try {
623     clone.buildFromSorted(size, entrySet().iterator(), null, null);
624     } catch (java.io.IOException cannotHappen) {
625     } catch (ClassNotFoundException cannotHappen) {
626     }
627    
628     return clone;
629     }
630    
631     // NavigableMap API methods
632    
633 jsr166 1.22 /**
634     * @since 1.6
635     */
636 dl 1.1 public Map.Entry<K,V> firstEntry() {
637 dl 1.33 return exportEntry(getFirstEntry());
638 dl 1.1 }
639    
640 jsr166 1.22 /**
641     * @since 1.6
642     */
643 dl 1.1 public Map.Entry<K,V> lastEntry() {
644 dl 1.33 return exportEntry(getLastEntry());
645 dl 1.1 }
646    
647 jsr166 1.22 /**
648     * @since 1.6
649     */
650 dl 1.1 public Map.Entry<K,V> pollFirstEntry() {
651     Entry<K,V> p = getFirstEntry();
652 dl 1.33 Map.Entry<K,V> result = exportEntry(p);
653     if (p != null)
654     deleteEntry(p);
655 dl 1.1 return result;
656     }
657    
658 jsr166 1.22 /**
659     * @since 1.6
660     */
661 dl 1.1 public Map.Entry<K,V> pollLastEntry() {
662     Entry<K,V> p = getLastEntry();
663 dl 1.33 Map.Entry<K,V> result = exportEntry(p);
664     if (p != null)
665     deleteEntry(p);
666 dl 1.1 return result;
667     }
668    
669     /**
670 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
671     * @throws NullPointerException if the specified key is null
672     * and this map uses natural ordering, or its comparator
673     * does not permit null keys
674 jsr166 1.22 * @since 1.6
675 dl 1.1 */
676 jsr166 1.14 public Map.Entry<K,V> lowerEntry(K key) {
677 dl 1.33 return exportEntry(getLowerEntry(key));
678 dl 1.1 }
679    
680     /**
681 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
682     * @throws NullPointerException if the specified key is null
683     * and this map uses natural ordering, or its comparator
684     * does not permit null keys
685 jsr166 1.22 * @since 1.6
686 dl 1.1 */
687 jsr166 1.14 public K lowerKey(K key) {
688 dl 1.33 return keyOrNull(getLowerEntry(key));
689 dl 1.1 }
690    
691     /**
692 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
693     * @throws NullPointerException if the specified key is null
694     * and this map uses natural ordering, or its comparator
695     * does not permit null keys
696 jsr166 1.22 * @since 1.6
697 dl 1.1 */
698     public Map.Entry<K,V> floorEntry(K key) {
699 dl 1.33 return exportEntry(getFloorEntry(key));
700 dl 1.1 }
701    
702     /**
703 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
704     * @throws NullPointerException if the specified key is null
705     * and this map uses natural ordering, or its comparator
706     * does not permit null keys
707 jsr166 1.22 * @since 1.6
708 dl 1.1 */
709     public K floorKey(K key) {
710 dl 1.33 return keyOrNull(getFloorEntry(key));
711 dl 1.1 }
712    
713     /**
714 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
715     * @throws NullPointerException if the specified key is null
716     * and this map uses natural ordering, or its comparator
717     * does not permit null keys
718 jsr166 1.22 * @since 1.6
719 dl 1.1 */
720 jsr166 1.14 public Map.Entry<K,V> ceilingEntry(K key) {
721 dl 1.33 return exportEntry(getCeilingEntry(key));
722 dl 1.1 }
723    
724     /**
725 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
726     * @throws NullPointerException if the specified key is null
727     * and this map uses natural ordering, or its comparator
728     * does not permit null keys
729 jsr166 1.22 * @since 1.6
730 dl 1.1 */
731 jsr166 1.14 public K ceilingKey(K key) {
732 dl 1.33 return keyOrNull(getCeilingEntry(key));
733 dl 1.1 }
734    
735     /**
736 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
737     * @throws NullPointerException if the specified key is null
738     * and this map uses natural ordering, or its comparator
739     * does not permit null keys
740 jsr166 1.22 * @since 1.6
741 dl 1.1 */
742 jsr166 1.14 public Map.Entry<K,V> higherEntry(K key) {
743 dl 1.33 return exportEntry(getHigherEntry(key));
744 dl 1.1 }
745    
746     /**
747 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
748     * @throws NullPointerException if the specified key is null
749     * and this map uses natural ordering, or its comparator
750     * does not permit null keys
751 jsr166 1.22 * @since 1.6
752 dl 1.1 */
753 jsr166 1.14 public K higherKey(K key) {
754 dl 1.33 return keyOrNull(getHigherEntry(key));
755 dl 1.1 }
756    
757     // Views
758    
759     /**
760     * Fields initialized to contain an instance of the entry set view
761     * the first time this view is requested. Views are stateless, so
762     * there's no reason to create more than one.
763     */
764 dl 1.29 private transient EntrySet entrySet = null;
765 dl 1.28 private transient KeySet<K> navigableKeySet = null;
766     private transient NavigableMap<K,V> descendingMap = null;
767 dl 1.1
768     /**
769 jsr166 1.14 * Returns a {@link Set} view of the keys contained in this map.
770     * The set's iterator returns the keys in ascending order.
771     * The set is backed by the map, so changes to the map are
772     * reflected in the set, and vice-versa. If the map is modified
773     * while an iteration over the set is in progress (except through
774     * the iterator's own <tt>remove</tt> operation), the results of
775     * the iteration are undefined. The set supports element removal,
776     * which removes the corresponding mapping from the map, via the
777     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
778 jsr166 1.15 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
779     * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
780 jsr166 1.14 * operations.
781 dl 1.1 */
782     public Set<K> keySet() {
783 dl 1.28 return navigableKeySet();
784 dl 1.1 }
785    
786 dl 1.28 /**
787     * @since 1.6
788     */
789     public NavigableSet<K> navigableKeySet() {
790 dl 1.29 KeySet<K> nks = navigableKeySet;
791 dl 1.28 return (nks != null) ? nks : (navigableKeySet = new KeySet(this));
792     }
793 dl 1.8
794 dl 1.28 /**
795     * @since 1.6
796     */
797     public NavigableSet<K> descendingKeySet() {
798     return descendingMap().navigableKeySet();
799 dl 1.1 }
800    
801     /**
802 jsr166 1.14 * Returns a {@link Collection} view of the values contained in this map.
803     * The collection's iterator returns the values in ascending order
804     * of the corresponding keys.
805     * The collection is backed by the map, so changes to the map are
806     * reflected in the collection, and vice-versa. If the map is
807     * modified while an iteration over the collection is in progress
808     * (except through the iterator's own <tt>remove</tt> operation),
809     * the results of the iteration are undefined. The collection
810     * supports element removal, which removes the corresponding
811     * mapping from the map, via the <tt>Iterator.remove</tt>,
812     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
813     * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
814 jsr166 1.15 * support the <tt>add</tt> or <tt>addAll</tt> operations.
815 dl 1.1 */
816     public Collection<V> values() {
817     Collection<V> vs = values;
818     return (vs != null) ? vs : (values = new Values());
819     }
820    
821     /**
822 jsr166 1.14 * Returns a {@link Set} view of the mappings contained in this map.
823     * The set's iterator returns the entries in ascending key order.
824     * The set is backed by the map, so changes to the map are
825     * reflected in the set, and vice-versa. If the map is modified
826     * while an iteration over the set is in progress (except through
827     * the iterator's own <tt>remove</tt> operation, or through the
828     * <tt>setValue</tt> operation on a map entry returned by the
829     * iterator) the results of the iteration are undefined. The set
830     * supports element removal, which removes the corresponding
831     * mapping from the map, via the <tt>Iterator.remove</tt>,
832 dl 1.1 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
833 jsr166 1.14 * <tt>clear</tt> operations. It does not support the
834     * <tt>add</tt> or <tt>addAll</tt> operations.
835 dl 1.1 */
836     public Set<Map.Entry<K,V>> entrySet() {
837 dl 1.29 EntrySet es = entrySet;
838 dl 1.1 return (es != null) ? es : (entrySet = new EntrySet());
839     }
840    
841 jsr166 1.22 /**
842     * @since 1.6
843     */
844 dl 1.28 public NavigableMap<K, V> descendingMap() {
845     NavigableMap<K, V> km = descendingMap;
846     return (km != null) ? km :
847 jsr166 1.30 (descendingMap = new DescendingSubMap(this,
848 dl 1.32 true, null, true,
849     true, null, true));
850 dl 1.1 }
851    
852     /**
853 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
854 dl 1.1 * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
855 jsr166 1.14 * null and this map uses natural ordering, or its comparator
856     * does not permit null keys
857     * @throws IllegalArgumentException {@inheritDoc}
858 jsr166 1.22 * @since 1.6
859 dl 1.1 */
860 dl 1.29 public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
861     K toKey, boolean toInclusive) {
862 jsr166 1.30 return new AscendingSubMap(this,
863 dl 1.32 false, fromKey, fromInclusive,
864     false, toKey, toInclusive);
865 dl 1.1 }
866    
867     /**
868 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
869     * @throws NullPointerException if <tt>toKey</tt> is null
870     * and this map uses natural ordering, or its comparator
871     * does not permit null keys
872     * @throws IllegalArgumentException {@inheritDoc}
873 jsr166 1.22 * @since 1.6
874 dl 1.1 */
875 dl 1.29 public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
876 jsr166 1.30 return new AscendingSubMap(this,
877 dl 1.32 true, null, true,
878     false, toKey, inclusive);
879 dl 1.1 }
880    
881     /**
882 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
883     * @throws NullPointerException if <tt>fromKey</tt> is null
884     * and this map uses natural ordering, or its comparator
885     * does not permit null keys
886     * @throws IllegalArgumentException {@inheritDoc}
887 jsr166 1.22 * @since 1.6
888 dl 1.1 */
889 dl 1.29 public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
890 jsr166 1.30 return new AscendingSubMap(this,
891 dl 1.32 false, fromKey, inclusive,
892     true, null, true);
893 dl 1.4 }
894    
895     /**
896 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
897 dl 1.4 * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
898 jsr166 1.14 * null and this map uses natural ordering, or its comparator
899     * does not permit null keys
900     * @throws IllegalArgumentException {@inheritDoc}
901 dl 1.4 */
902     public SortedMap<K,V> subMap(K fromKey, K toKey) {
903 dl 1.29 return subMap(fromKey, true, toKey, false);
904 dl 1.4 }
905    
906     /**
907 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
908     * @throws NullPointerException if <tt>toKey</tt> is null
909     * and this map uses natural ordering, or its comparator
910     * does not permit null keys
911     * @throws IllegalArgumentException {@inheritDoc}
912 dl 1.4 */
913     public SortedMap<K,V> headMap(K toKey) {
914 dl 1.29 return headMap(toKey, false);
915 dl 1.4 }
916    
917     /**
918 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
919     * @throws NullPointerException if <tt>fromKey</tt> is null
920     * and this map uses natural ordering, or its comparator
921     * does not permit null keys
922     * @throws IllegalArgumentException {@inheritDoc}
923 dl 1.4 */
924     public SortedMap<K,V> tailMap(K fromKey) {
925 dl 1.29 return tailMap(fromKey, true);
926 dl 1.1 }
927    
928 dl 1.28 // View class support
929 dl 1.1
930 dl 1.28 class Values extends AbstractCollection<V> {
931     public Iterator<V> iterator() {
932     return new ValueIterator(getFirstEntry());
933     }
934 dl 1.1
935 dl 1.28 public int size() {
936     return TreeMap.this.size();
937 dl 1.1 }
938    
939 dl 1.28 public boolean contains(Object o) {
940 dl 1.34 return TreeMap.this.containsValue(o);
941 dl 1.28 }
942 dl 1.1
943 dl 1.28 public boolean remove(Object o) {
944     for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
945     if (valEquals(e.getValue(), o)) {
946     deleteEntry(e);
947     return true;
948     }
949 dl 1.1 }
950 dl 1.28 return false;
951 dl 1.1 }
952    
953 dl 1.28 public void clear() {
954     TreeMap.this.clear();
955     }
956     }
957    
958     class EntrySet extends AbstractSet<Map.Entry<K,V>> {
959     public Iterator<Map.Entry<K,V>> iterator() {
960     return new EntryIterator(getFirstEntry());
961 dl 1.1 }
962    
963 dl 1.28 public boolean contains(Object o) {
964     if (!(o instanceof Map.Entry))
965     return false;
966     Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
967     V value = entry.getValue();
968     Entry<K,V> p = getEntry(entry.getKey());
969     return p != null && valEquals(p.getValue(), value);
970 dl 1.1 }
971    
972 dl 1.28 public boolean remove(Object o) {
973     if (!(o instanceof Map.Entry))
974     return false;
975     Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
976     V value = entry.getValue();
977     Entry<K,V> p = getEntry(entry.getKey());
978     if (p != null && valEquals(p.getValue(), value)) {
979     deleteEntry(p);
980     return true;
981     }
982     return false;
983 dl 1.1 }
984    
985 dl 1.28 public int size() {
986     return TreeMap.this.size();
987 dl 1.1 }
988    
989 dl 1.28 public void clear() {
990     TreeMap.this.clear();
991 dl 1.1 }
992 dl 1.28 }
993    
994     /*
995     * Unlike Values and EntrySet, the KeySet class is static,
996     * delegating to a NavigableMap to allow use by SubMaps, which
997     * outweighs the ugliness of needing type-tests for the following
998     * Iterator methods that are defined appropriately in main versus
999     * submap classes.
1000     */
1001 dl 1.1
1002 dl 1.28 Iterator<K> keyIterator() {
1003     return new KeyIterator(getFirstEntry());
1004     }
1005    
1006     Iterator<K> descendingKeyIterator() {
1007     return new DescendingKeyIterator(getFirstEntry());
1008     }
1009    
1010     static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
1011     private final NavigableMap<E, Object> m;
1012     KeySet(NavigableMap<E,Object> map) { m = map; }
1013    
1014     public Iterator<E> iterator() {
1015     if (m instanceof TreeMap)
1016     return ((TreeMap<E,Object>)m).keyIterator();
1017     else
1018     return (Iterator<E>)(((TreeMap.NavigableSubMap)m).keyIterator());
1019 dl 1.1 }
1020    
1021 dl 1.28 public Iterator<E> descendingIterator() {
1022     if (m instanceof TreeMap)
1023     return ((TreeMap<E,Object>)m).descendingKeyIterator();
1024     else
1025     return (Iterator<E>)(((TreeMap.NavigableSubMap)m).descendingKeyIterator());
1026 dl 1.1 }
1027    
1028 dl 1.28 public int size() { return m.size(); }
1029     public boolean isEmpty() { return m.isEmpty(); }
1030     public boolean contains(Object o) { return m.containsKey(o); }
1031     public void clear() { m.clear(); }
1032     public E lower(E e) { return m.lowerKey(e); }
1033     public E floor(E e) { return m.floorKey(e); }
1034     public E ceiling(E e) { return m.ceilingKey(e); }
1035     public E higher(E e) { return m.higherKey(e); }
1036     public E first() { return m.firstKey(); }
1037     public E last() { return m.lastKey(); }
1038     public Comparator<? super E> comparator() { return m.comparator(); }
1039     public E pollFirst() {
1040     Map.Entry<E,Object> e = m.pollFirstEntry();
1041     return e == null? null : e.getKey();
1042     }
1043     public E pollLast() {
1044     Map.Entry<E,Object> e = m.pollLastEntry();
1045     return e == null? null : e.getKey();
1046     }
1047     public boolean remove(Object o) {
1048     int oldSize = size();
1049     m.remove(o);
1050     return size() != oldSize;
1051     }
1052 dl 1.31 public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
1053 jsr166 1.36 E toElement, boolean toInclusive) {
1054 dl 1.31 return new TreeSet<E>(m.subMap(fromElement, fromInclusive,
1055     toElement, toInclusive));
1056 dl 1.28 }
1057 dl 1.29 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1058     return new TreeSet<E>(m.headMap(toElement, inclusive));
1059 dl 1.28 }
1060 dl 1.29 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1061     return new TreeSet<E>(m.tailMap(fromElement, inclusive));
1062 dl 1.28 }
1063     public SortedSet<E> subSet(E fromElement, E toElement) {
1064 dl 1.29 return subSet(fromElement, true, toElement, false);
1065 dl 1.28 }
1066     public SortedSet<E> headSet(E toElement) {
1067 dl 1.29 return headSet(toElement, false);
1068 dl 1.28 }
1069     public SortedSet<E> tailSet(E fromElement) {
1070 dl 1.29 return tailSet(fromElement, true);
1071 dl 1.28 }
1072     public NavigableSet<E> descendingSet() {
1073     return new TreeSet(m.descendingMap());
1074 dl 1.1 }
1075 dl 1.28 }
1076    
1077 dl 1.29 /**
1078     * Base class for TreeMap Iterators
1079     */
1080     abstract class PrivateEntryIterator<T> implements Iterator<T> {
1081     Entry<K,V> next;
1082 dl 1.31 Entry<K,V> lastReturned;
1083     int expectedModCount;
1084 dl 1.29
1085     PrivateEntryIterator(Entry<K,V> first) {
1086 dl 1.31 expectedModCount = modCount;
1087     lastReturned = null;
1088 dl 1.29 next = first;
1089     }
1090    
1091     public final boolean hasNext() {
1092     return next != null;
1093     }
1094    
1095     final Entry<K,V> nextEntry() {
1096 dl 1.31 Entry<K,V> e = lastReturned = next;
1097     if (e == null)
1098 dl 1.29 throw new NoSuchElementException();
1099     if (modCount != expectedModCount)
1100     throw new ConcurrentModificationException();
1101 dl 1.31 next = successor(e);
1102     return e;
1103 dl 1.29 }
1104    
1105     final Entry<K,V> prevEntry() {
1106 dl 1.31 Entry<K,V> e = lastReturned= next;
1107     if (e == null)
1108 dl 1.29 throw new NoSuchElementException();
1109     if (modCount != expectedModCount)
1110     throw new ConcurrentModificationException();
1111 dl 1.31 next = predecessor(e);
1112     return e;
1113 dl 1.29 }
1114    
1115     public void remove() {
1116     if (lastReturned == null)
1117     throw new IllegalStateException();
1118     if (modCount != expectedModCount)
1119     throw new ConcurrentModificationException();
1120 dl 1.37 // deleted entries are replaced by their successors
1121 dl 1.29 if (lastReturned.left != null && lastReturned.right != null)
1122     next = lastReturned;
1123     deleteEntry(lastReturned);
1124 jsr166 1.38 expectedModCount = modCount;
1125 dl 1.29 lastReturned = null;
1126     }
1127     }
1128    
1129     final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1130     EntryIterator(Entry<K,V> first) {
1131     super(first);
1132     }
1133     public Map.Entry<K,V> next() {
1134     return nextEntry();
1135     }
1136     }
1137    
1138     final class ValueIterator extends PrivateEntryIterator<V> {
1139     ValueIterator(Entry<K,V> first) {
1140     super(first);
1141     }
1142     public V next() {
1143     return nextEntry().value;
1144     }
1145     }
1146    
1147     final class KeyIterator extends PrivateEntryIterator<K> {
1148     KeyIterator(Entry<K,V> first) {
1149     super(first);
1150     }
1151     public K next() {
1152     return nextEntry().key;
1153     }
1154     }
1155    
1156     final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1157     DescendingKeyIterator(Entry<K,V> first) {
1158     super(first);
1159     }
1160     public K next() {
1161     return prevEntry().key;
1162     }
1163     }
1164    
1165 dl 1.33 // Little utilities
1166    
1167     /**
1168     * Compares two keys using the correct comparison method for this TreeMap.
1169     */
1170     final int compare(Object k1, Object k2) {
1171     return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1172     : comparator.compare((K)k1, (K)k2);
1173     }
1174    
1175     /**
1176     * Test two values for equality. Differs from o1.equals(o2) only in
1177     * that it copes with <tt>null</tt> o1 properly.
1178     */
1179     final static boolean valEquals(Object o1, Object o2) {
1180     return (o1==null ? o2==null : o1.equals(o2));
1181     }
1182    
1183     /**
1184     * Return SimpleImmutableEntry for entry, or null if null
1185     */
1186     static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
1187     return e == null? null :
1188     new AbstractMap.SimpleImmutableEntry<K,V>(e);
1189     }
1190    
1191     /**
1192     * Return key for entry, or null if null
1193     */
1194     static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
1195     return e == null? null : e.key;
1196     }
1197    
1198     /**
1199     * Returns the key corresponding to the specified Entry.
1200     * @throws NoSuchElementException if the Entry is null
1201     */
1202     static <K> K key(Entry<K,?> e) {
1203     if (e==null)
1204     throw new NoSuchElementException();
1205     return e.key;
1206     }
1207    
1208    
1209 dl 1.28 // SubMaps
1210    
1211 jsr166 1.36 /**
1212 jsr166 1.42 * Dummy value serving as unmatchable fence key for unbounded
1213     * SubMapIterators
1214     */
1215     private static final Object UNBOUNDED = new Object();
1216    
1217     /**
1218 jsr166 1.36 * @serial include
1219     */
1220 dl 1.29 static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
1221 dl 1.28 implements NavigableMap<K,V>, java.io.Serializable {
1222 jsr166 1.36 /**
1223 dl 1.29 * The backing map.
1224     */
1225 jsr166 1.30 final TreeMap<K,V> m;
1226 dl 1.29
1227 jsr166 1.36 /**
1228 dl 1.32 * Endpoints are represented as triples (fromStart, lo,
1229     * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is
1230     * true, then the low (absolute) bound is the start of the
1231     * backing map, and the other values are ignored. Otherwise,
1232     * if loInclusive is true, lo is the inclusive bound, else lo
1233     * is the exclusive bound. Similarly for the upper bound.
1234 dl 1.28 */
1235 dl 1.31 final K lo, hi;
1236     final boolean fromStart, toEnd;
1237 dl 1.32 final boolean loInclusive, hiInclusive;
1238 dl 1.28
1239 jsr166 1.30 NavigableSubMap(TreeMap<K,V> m,
1240 dl 1.32 boolean fromStart, K lo, boolean loInclusive,
1241     boolean toEnd, K hi, boolean hiInclusive) {
1242 dl 1.31 if (!fromStart && !toEnd) {
1243     if (m.compare(lo, hi) > 0)
1244     throw new IllegalArgumentException("fromKey > toKey");
1245 dl 1.32 } else {
1246     if (!fromStart) // type check
1247     m.compare(lo, lo);
1248     if (!toEnd)
1249     m.compare(hi, hi);
1250 dl 1.31 }
1251    
1252 dl 1.29 this.m = m;
1253     this.fromStart = fromStart;
1254 dl 1.28 this.lo = lo;
1255 dl 1.32 this.loInclusive = loInclusive;
1256 dl 1.29 this.toEnd = toEnd;
1257 dl 1.28 this.hi = hi;
1258 dl 1.32 this.hiInclusive = hiInclusive;
1259 dl 1.1 }
1260    
1261 dl 1.29 // internal utilities
1262    
1263 dl 1.32 final boolean tooLow(Object key) {
1264     if (!fromStart) {
1265     int c = m.compare(key, lo);
1266     if (c < 0 || (c == 0 && !loInclusive))
1267     return true;
1268     }
1269     return false;
1270     }
1271    
1272     final boolean tooHigh(Object key) {
1273     if (!toEnd) {
1274     int c = m.compare(key, hi);
1275     if (c > 0 || (c == 0 && !hiInclusive))
1276     return true;
1277     }
1278     return false;
1279     }
1280    
1281 dl 1.29 final boolean inRange(Object key) {
1282 dl 1.32 return !tooLow(key) && !tooHigh(key);
1283 dl 1.29 }
1284    
1285     final boolean inClosedRange(Object key) {
1286     return (fromStart || m.compare(key, lo) >= 0)
1287     && (toEnd || m.compare(hi, key) >= 0);
1288     }
1289    
1290     final boolean inRange(Object key, boolean inclusive) {
1291     return inclusive ? inRange(key) : inClosedRange(key);
1292     }
1293    
1294 dl 1.32 /*
1295     * Absolute versions of relation operations.
1296     * Subclasses map to these using like-named "sub"
1297     * versions that invert senses for descending maps
1298     */
1299    
1300     final TreeMap.Entry<K,V> absLowest() {
1301     TreeMap.Entry<K,V> e =
1302 dl 1.29 (fromStart ? m.getFirstEntry() :
1303 dl 1.32 (loInclusive ? m.getCeilingEntry(lo) :
1304     m.getHigherEntry(lo)));
1305     return (e == null || tooHigh(e.key)) ? null : e;
1306 dl 1.29 }
1307    
1308 dl 1.32 final TreeMap.Entry<K,V> absHighest() {
1309     TreeMap.Entry<K,V> e =
1310 dl 1.29 (toEnd ? m.getLastEntry() :
1311 dl 1.32 (hiInclusive ? m.getFloorEntry(hi) :
1312     m.getLowerEntry(hi)));
1313     return (e == null || tooLow(e.key)) ? null : e;
1314     }
1315 dl 1.33
1316 dl 1.32 final TreeMap.Entry<K,V> absCeiling(K key) {
1317     if (tooLow(key))
1318     return absLowest();
1319     TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
1320     return (e == null || tooHigh(e.key)) ? null : e;
1321 dl 1.29 }
1322    
1323 dl 1.32 final TreeMap.Entry<K,V> absHigher(K key) {
1324     if (tooLow(key))
1325     return absLowest();
1326     TreeMap.Entry<K,V> e = m.getHigherEntry(key);
1327     return (e == null || tooHigh(e.key)) ? null : e;
1328 dl 1.29 }
1329    
1330 dl 1.32 final TreeMap.Entry<K,V> absFloor(K key) {
1331     if (tooHigh(key))
1332     return absHighest();
1333     TreeMap.Entry<K,V> e = m.getFloorEntry(key);
1334     return (e == null || tooLow(e.key)) ? null : e;
1335 dl 1.29 }
1336    
1337 dl 1.32 final TreeMap.Entry<K,V> absLower(K key) {
1338     if (tooHigh(key))
1339     return absHighest();
1340     TreeMap.Entry<K,V> e = m.getLowerEntry(key);
1341     return (e == null || tooLow(e.key)) ? null : e;
1342 dl 1.29 }
1343    
1344 dl 1.32 /** Returns the absolute high fence for ascending traversal */
1345     final TreeMap.Entry<K,V> absHighFence() {
1346 dl 1.33 return (toEnd ? null : (hiInclusive ?
1347 dl 1.32 m.getHigherEntry(hi) :
1348     m.getCeilingEntry(hi)));
1349     }
1350    
1351     /** Return the absolute low fence for descending traversal */
1352     final TreeMap.Entry<K,V> absLowFence() {
1353     return (fromStart ? null : (loInclusive ?
1354     m.getLowerEntry(lo) :
1355     m.getFloorEntry(lo)));
1356     }
1357    
1358     // Abstract methods defined in ascending vs descending classes
1359 jsr166 1.36 // These relay to the appropriate absolute versions
1360 dl 1.32
1361     abstract TreeMap.Entry<K,V> subLowest();
1362     abstract TreeMap.Entry<K,V> subHighest();
1363     abstract TreeMap.Entry<K,V> subCeiling(K key);
1364     abstract TreeMap.Entry<K,V> subHigher(K key);
1365     abstract TreeMap.Entry<K,V> subFloor(K key);
1366     abstract TreeMap.Entry<K,V> subLower(K key);
1367    
1368     /** Returns ascending iterator from the perspective of this submap */
1369     abstract Iterator<K> keyIterator();
1370    
1371     /** Returns descending iterator from the perspective of this submap */
1372     abstract Iterator<K> descendingKeyIterator();
1373 dl 1.29
1374 dl 1.32 // public methods
1375 dl 1.29
1376 dl 1.28 public boolean isEmpty() {
1377 dl 1.32 return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1378 dl 1.1 }
1379    
1380 dl 1.32 public int size() {
1381     return (fromStart && toEnd) ? m.size() : entrySet().size();
1382 dl 1.1 }
1383    
1384 dl 1.32 public final boolean containsKey(Object key) {
1385     return inRange(key) && m.containsKey(key);
1386 dl 1.1 }
1387    
1388 dl 1.32 public final V put(K key, V value) {
1389 dl 1.28 if (!inRange(key))
1390     throw new IllegalArgumentException("key out of range");
1391 dl 1.29 return m.put(key, value);
1392 dl 1.1 }
1393    
1394 dl 1.32 public final V get(Object key) {
1395     return !inRange(key)? null : m.get(key);
1396     }
1397    
1398     public final V remove(Object key) {
1399     return !inRange(key)? null : m.remove(key);
1400     }
1401    
1402     public final Map.Entry<K,V> ceilingEntry(K key) {
1403     return exportEntry(subCeiling(key));
1404     }
1405    
1406     public final K ceilingKey(K key) {
1407 dl 1.33 return keyOrNull(subCeiling(key));
1408 dl 1.32 }
1409    
1410     public final Map.Entry<K,V> higherEntry(K key) {
1411     return exportEntry(subHigher(key));
1412     }
1413    
1414     public final K higherKey(K key) {
1415 dl 1.33 return keyOrNull(subHigher(key));
1416 dl 1.1 }
1417    
1418 dl 1.32 public final Map.Entry<K,V> floorEntry(K key) {
1419     return exportEntry(subFloor(key));
1420 dl 1.1 }
1421    
1422 dl 1.32 public final K floorKey(K key) {
1423 dl 1.33 return keyOrNull(subFloor(key));
1424 dl 1.1 }
1425    
1426 dl 1.32 public final Map.Entry<K,V> lowerEntry(K key) {
1427     return exportEntry(subLower(key));
1428 dl 1.1 }
1429    
1430 dl 1.32 public final K lowerKey(K key) {
1431 dl 1.33 return keyOrNull(subLower(key));
1432 dl 1.1 }
1433    
1434 dl 1.32 public final K firstKey() {
1435     return key(subLowest());
1436 dl 1.1 }
1437    
1438 dl 1.32 public final K lastKey() {
1439     return key(subHighest());
1440 dl 1.1 }
1441    
1442 dl 1.32 public final Map.Entry<K,V> firstEntry() {
1443     return exportEntry(subLowest());
1444 dl 1.1 }
1445    
1446 dl 1.32 public final Map.Entry<K,V> lastEntry() {
1447     return exportEntry(subHighest());
1448 dl 1.1 }
1449    
1450 dl 1.32 public final Map.Entry<K,V> pollFirstEntry() {
1451     TreeMap.Entry<K,V> e = subLowest();
1452     Map.Entry<K,V> result = exportEntry(e);
1453     if (e != null)
1454     m.deleteEntry(e);
1455     return result;
1456     }
1457 dl 1.1
1458 dl 1.32 public final Map.Entry<K,V> pollLastEntry() {
1459     TreeMap.Entry<K,V> e = subHighest();
1460     Map.Entry<K,V> result = exportEntry(e);
1461     if (e != null)
1462     m.deleteEntry(e);
1463     return result;
1464 dl 1.1 }
1465    
1466 dl 1.28 // Views
1467     transient NavigableMap<K,V> descendingMapView = null;
1468 dl 1.29 transient EntrySetView entrySetView = null;
1469     transient KeySet<K> navigableKeySetView = null;
1470 dl 1.28
1471 dl 1.32 public final NavigableSet<K> navigableKeySet() {
1472     KeySet<K> nksv = navigableKeySetView;
1473     return (nksv != null) ? nksv :
1474     (navigableKeySetView = new TreeMap.KeySet(this));
1475     }
1476    
1477     public final Set<K> keySet() {
1478     return navigableKeySet();
1479     }
1480    
1481     public NavigableSet<K> descendingKeySet() {
1482     return descendingMap().navigableKeySet();
1483     }
1484    
1485     public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1486     return subMap(fromKey, true, toKey, false);
1487     }
1488    
1489     public final SortedMap<K,V> headMap(K toKey) {
1490     return headMap(toKey, false);
1491     }
1492    
1493     public final SortedMap<K,V> tailMap(K fromKey) {
1494     return tailMap(fromKey, true);
1495     }
1496    
1497     // View classes
1498    
1499 dl 1.28 abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1500 dl 1.1 private transient int size = -1, sizeModCount;
1501    
1502     public int size() {
1503 dl 1.29 if (fromStart && toEnd)
1504     return m.size();
1505     if (size == -1 || sizeModCount != m.modCount) {
1506     sizeModCount = m.modCount;
1507 jsr166 1.30 size = 0;
1508 dl 1.1 Iterator i = iterator();
1509     while (i.hasNext()) {
1510     size++;
1511     i.next();
1512     }
1513     }
1514     return size;
1515     }
1516    
1517     public boolean isEmpty() {
1518 dl 1.32 TreeMap.Entry<K,V> n = absLowest();
1519 dl 1.29 return n == null || tooHigh(n.key);
1520 dl 1.1 }
1521    
1522     public boolean contains(Object o) {
1523     if (!(o instanceof Map.Entry))
1524     return false;
1525     Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1526     K key = entry.getKey();
1527     if (!inRange(key))
1528     return false;
1529 dl 1.29 TreeMap.Entry node = m.getEntry(key);
1530 dl 1.1 return node != null &&
1531 dl 1.29 valEquals(node.getValue(), entry.getValue());
1532 dl 1.1 }
1533    
1534     public boolean remove(Object o) {
1535     if (!(o instanceof Map.Entry))
1536     return false;
1537     Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1538     K key = entry.getKey();
1539     if (!inRange(key))
1540     return false;
1541 dl 1.29 TreeMap.Entry<K,V> node = m.getEntry(key);
1542 dl 1.1 if (node!=null && valEquals(node.getValue(),entry.getValue())){
1543 dl 1.29 m.deleteEntry(node);
1544 dl 1.1 return true;
1545     }
1546     return false;
1547     }
1548 dl 1.28 }
1549 dl 1.1
1550 dl 1.29 /**
1551     * Iterators for SubMaps
1552     */
1553     abstract class SubMapIterator<T> implements Iterator<T> {
1554 dl 1.31 TreeMap.Entry<K,V> lastReturned;
1555 dl 1.29 TreeMap.Entry<K,V> next;
1556 jsr166 1.42 final Object fenceKey;
1557 dl 1.31 int expectedModCount;
1558 dl 1.29
1559 jsr166 1.30 SubMapIterator(TreeMap.Entry<K,V> first,
1560 dl 1.31 TreeMap.Entry<K,V> fence) {
1561     expectedModCount = m.modCount;
1562     lastReturned = null;
1563 dl 1.29 next = first;
1564 jsr166 1.42 fenceKey = fence == null ? UNBOUNDED : fence.key;
1565 dl 1.29 }
1566    
1567     public final boolean hasNext() {
1568 dl 1.31 return next != null && next.key != fenceKey;
1569 dl 1.29 }
1570    
1571     final TreeMap.Entry<K,V> nextEntry() {
1572 dl 1.31 TreeMap.Entry<K,V> e = lastReturned = next;
1573     if (e == null || e.key == fenceKey)
1574 dl 1.29 throw new NoSuchElementException();
1575     if (m.modCount != expectedModCount)
1576     throw new ConcurrentModificationException();
1577 dl 1.31 next = successor(e);
1578     return e;
1579 dl 1.29 }
1580    
1581     final TreeMap.Entry<K,V> prevEntry() {
1582 dl 1.31 TreeMap.Entry<K,V> e = lastReturned = next;
1583     if (e == null || e.key == fenceKey)
1584 dl 1.29 throw new NoSuchElementException();
1585     if (m.modCount != expectedModCount)
1586     throw new ConcurrentModificationException();
1587 dl 1.31 next = predecessor(e);
1588     return e;
1589 dl 1.29 }
1590    
1591 dl 1.37 final void removeAscending() {
1592 dl 1.29 if (lastReturned == null)
1593     throw new IllegalStateException();
1594     if (m.modCount != expectedModCount)
1595     throw new ConcurrentModificationException();
1596 dl 1.37 // deleted entries are replaced by their successors
1597 dl 1.29 if (lastReturned.left != null && lastReturned.right != null)
1598     next = lastReturned;
1599     m.deleteEntry(lastReturned);
1600     lastReturned = null;
1601 dl 1.37 expectedModCount = m.modCount;
1602     }
1603    
1604     final void removeDescending() {
1605     if (lastReturned == null)
1606     throw new IllegalStateException();
1607     if (m.modCount != expectedModCount)
1608     throw new ConcurrentModificationException();
1609     m.deleteEntry(lastReturned);
1610     lastReturned = null;
1611     expectedModCount = m.modCount;
1612 dl 1.29 }
1613 dl 1.37
1614 dl 1.28 }
1615    
1616 dl 1.29 final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1617 jsr166 1.30 SubMapEntryIterator(TreeMap.Entry<K,V> first,
1618 dl 1.31 TreeMap.Entry<K,V> fence) {
1619     super(first, fence);
1620 dl 1.29 }
1621     public Map.Entry<K,V> next() {
1622     return nextEntry();
1623     }
1624 dl 1.37 public void remove() {
1625     removeAscending();
1626     }
1627 dl 1.28 }
1628    
1629 dl 1.29 final class SubMapKeyIterator extends SubMapIterator<K> {
1630 jsr166 1.30 SubMapKeyIterator(TreeMap.Entry<K,V> first,
1631 dl 1.31 TreeMap.Entry<K,V> fence) {
1632     super(first, fence);
1633 dl 1.29 }
1634     public K next() {
1635     return nextEntry().key;
1636     }
1637 dl 1.37 public void remove() {
1638     removeAscending();
1639     }
1640 dl 1.28 }
1641    
1642 dl 1.29 final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1643 jsr166 1.30 DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
1644 dl 1.32 TreeMap.Entry<K,V> fence) {
1645     super(last, fence);
1646 dl 1.29 }
1647    
1648     public Map.Entry<K,V> next() {
1649     return prevEntry();
1650     }
1651 dl 1.37 public void remove() {
1652     removeDescending();
1653     }
1654 dl 1.28 }
1655    
1656 dl 1.29 final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
1657 jsr166 1.30 DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
1658 dl 1.32 TreeMap.Entry<K,V> fence) {
1659     super(last, fence);
1660 dl 1.29 }
1661     public K next() {
1662     return prevEntry().key;
1663     }
1664 dl 1.37 public void remove() {
1665     removeDescending();
1666     }
1667 dl 1.28 }
1668     }
1669    
1670 jsr166 1.36 /**
1671     * @serial include
1672     */
1673 dl 1.32 static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1674 dl 1.28 private static final long serialVersionUID = 912986545866124060L;
1675    
1676 jsr166 1.30 AscendingSubMap(TreeMap<K,V> m,
1677 dl 1.32 boolean fromStart, K lo, boolean loInclusive,
1678 jsr166 1.36 boolean toEnd, K hi, boolean hiInclusive) {
1679 dl 1.32 super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1680 dl 1.28 }
1681    
1682     public Comparator<? super K> comparator() {
1683 dl 1.29 return m.comparator();
1684 dl 1.28 }
1685    
1686 jsr166 1.30 public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1687 jsr166 1.36 K toKey, boolean toInclusive) {
1688 dl 1.28 if (!inRange(fromKey, fromInclusive))
1689     throw new IllegalArgumentException("fromKey out of range");
1690     if (!inRange(toKey, toInclusive))
1691     throw new IllegalArgumentException("toKey out of range");
1692 jsr166 1.30 return new AscendingSubMap(m,
1693 dl 1.32 false, fromKey, fromInclusive,
1694     false, toKey, toInclusive);
1695 dl 1.28 }
1696    
1697 dl 1.29 public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1698 dl 1.39 if (!inRange(toKey, inclusive))
1699 dl 1.28 throw new IllegalArgumentException("toKey out of range");
1700 jsr166 1.30 return new AscendingSubMap(m,
1701 dl 1.32 fromStart, lo, loInclusive,
1702     false, toKey, inclusive);
1703 dl 1.28 }
1704    
1705 dl 1.29 public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1706 dl 1.28 if (!inRange(fromKey, inclusive))
1707     throw new IllegalArgumentException("fromKey out of range");
1708 jsr166 1.30 return new AscendingSubMap(m,
1709 dl 1.32 false, fromKey, inclusive,
1710     toEnd, hi, hiInclusive);
1711     }
1712    
1713     public NavigableMap<K,V> descendingMap() {
1714     NavigableMap<K,V> mv = descendingMapView;
1715     return (mv != null) ? mv :
1716     (descendingMapView =
1717     new DescendingSubMap(m,
1718     fromStart, lo, loInclusive,
1719     toEnd, hi, hiInclusive));
1720 dl 1.28 }
1721    
1722     Iterator<K> keyIterator() {
1723 dl 1.32 return new SubMapKeyIterator(absLowest(), absHighFence());
1724 dl 1.28 }
1725    
1726     Iterator<K> descendingKeyIterator() {
1727 dl 1.32 return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1728 dl 1.29 }
1729    
1730 dl 1.32 final class AscendingEntrySetView extends EntrySetView {
1731 dl 1.29 public Iterator<Map.Entry<K,V>> iterator() {
1732 dl 1.32 return new SubMapEntryIterator(absLowest(), absHighFence());
1733 dl 1.29 }
1734 dl 1.28 }
1735    
1736     public Set<Map.Entry<K,V>> entrySet() {
1737 dl 1.29 EntrySetView es = entrySetView;
1738     return (es != null) ? es : new AscendingEntrySetView();
1739 dl 1.28 }
1740    
1741 dl 1.32 TreeMap.Entry<K,V> subLowest() { return absLowest(); }
1742     TreeMap.Entry<K,V> subHighest() { return absHighest(); }
1743     TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); }
1744     TreeMap.Entry<K,V> subHigher(K key) { return absHigher(key); }
1745     TreeMap.Entry<K,V> subFloor(K key) { return absFloor(key); }
1746     TreeMap.Entry<K,V> subLower(K key) { return absLower(key); }
1747 dl 1.28 }
1748 dl 1.1
1749 jsr166 1.36 /**
1750     * @serial include
1751     */
1752 dl 1.32 static final class DescendingSubMap<K,V> extends NavigableSubMap<K,V> {
1753 dl 1.28 private static final long serialVersionUID = 912986545866120460L;
1754 jsr166 1.30 DescendingSubMap(TreeMap<K,V> m,
1755 dl 1.32 boolean fromStart, K lo, boolean loInclusive,
1756 jsr166 1.36 boolean toEnd, K hi, boolean hiInclusive) {
1757 dl 1.32 super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1758 dl 1.28 }
1759 dl 1.8
1760 dl 1.28 private final Comparator<? super K> reverseComparator =
1761 dl 1.29 Collections.reverseOrder(m.comparator);
1762 dl 1.8
1763 dl 1.28 public Comparator<? super K> comparator() {
1764     return reverseComparator;
1765 dl 1.1 }
1766    
1767 jsr166 1.30 public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1768 jsr166 1.36 K toKey, boolean toInclusive) {
1769 dl 1.28 if (!inRange(fromKey, fromInclusive))
1770 dl 1.1 throw new IllegalArgumentException("fromKey out of range");
1771 dl 1.28 if (!inRange(toKey, toInclusive))
1772 dl 1.1 throw new IllegalArgumentException("toKey out of range");
1773 jsr166 1.30 return new DescendingSubMap(m,
1774 dl 1.32 false, toKey, toInclusive,
1775     false, fromKey, fromInclusive);
1776 dl 1.1 }
1777    
1778 dl 1.29 public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1779 dl 1.28 if (!inRange(toKey, inclusive))
1780 dl 1.1 throw new IllegalArgumentException("toKey out of range");
1781 jsr166 1.30 return new DescendingSubMap(m,
1782 dl 1.32 false, toKey, inclusive,
1783     toEnd, hi, hiInclusive);
1784 dl 1.1 }
1785    
1786 dl 1.29 public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1787 dl 1.28 if (!inRange(fromKey, inclusive))
1788 dl 1.1 throw new IllegalArgumentException("fromKey out of range");
1789 jsr166 1.30 return new DescendingSubMap(m,
1790 dl 1.32 fromStart, lo, loInclusive,
1791     false, fromKey, inclusive);
1792     }
1793    
1794     public NavigableMap<K,V> descendingMap() {
1795     NavigableMap<K,V> mv = descendingMapView;
1796     return (mv != null) ? mv :
1797     (descendingMapView =
1798     new AscendingSubMap(m,
1799     fromStart, lo, loInclusive,
1800     toEnd, hi, hiInclusive));
1801 dl 1.28 }
1802    
1803     Iterator<K> keyIterator() {
1804 dl 1.32 return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1805 dl 1.28 }
1806    
1807     Iterator<K> descendingKeyIterator() {
1808 dl 1.32 return new SubMapKeyIterator(absLowest(), absHighFence());
1809 dl 1.29 }
1810    
1811 dl 1.32 final class DescendingEntrySetView extends EntrySetView {
1812 dl 1.29 public Iterator<Map.Entry<K,V>> iterator() {
1813 dl 1.32 return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
1814 dl 1.29 }
1815 dl 1.28 }
1816    
1817     public Set<Map.Entry<K,V>> entrySet() {
1818 dl 1.29 EntrySetView es = entrySetView;
1819     return (es != null) ? es : new DescendingEntrySetView();
1820 dl 1.28 }
1821    
1822 dl 1.32 TreeMap.Entry<K,V> subLowest() { return absHighest(); }
1823     TreeMap.Entry<K,V> subHighest() { return absLowest(); }
1824     TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
1825     TreeMap.Entry<K,V> subHigher(K key) { return absLower(key); }
1826     TreeMap.Entry<K,V> subFloor(K key) { return absCeiling(key); }
1827     TreeMap.Entry<K,V> subLower(K key) { return absHigher(key); }
1828 dl 1.1 }
1829    
1830     /**
1831 dl 1.28 * This class exists solely for the sake of serialization
1832     * compatibility with previous releases of TreeMap that did not
1833     * support NavigableMap. It translates an old-version SubMap into
1834     * a new-version AscendingSubMap. This class is never otherwise
1835     * used.
1836 jsr166 1.36 *
1837     * @serial include
1838 dl 1.28 */
1839     private class SubMap extends AbstractMap<K,V>
1840     implements SortedMap<K,V>, java.io.Serializable {
1841     private static final long serialVersionUID = -6520786458950516097L;
1842     private boolean fromStart = false, toEnd = false;
1843     private K fromKey, toKey;
1844     private Object readResolve() {
1845 jsr166 1.30 return new AscendingSubMap(TreeMap.this,
1846 dl 1.32 fromStart, fromKey, true,
1847     toEnd, toKey, false);
1848 dl 1.29 }
1849     public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
1850     public K lastKey() { throw new InternalError(); }
1851     public K firstKey() { throw new InternalError(); }
1852     public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
1853     public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
1854     public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
1855     public Comparator<? super K> comparator() { throw new InternalError(); }
1856 dl 1.1 }
1857    
1858    
1859 dl 1.33 // Red-black mechanics
1860    
1861 dl 1.1 private static final boolean RED = false;
1862     private static final boolean BLACK = true;
1863    
1864     /**
1865     * Node in the Tree. Doubles as a means to pass key-value pairs back to
1866     * user (see Map.Entry).
1867     */
1868    
1869 dl 1.29 static final class Entry<K,V> implements Map.Entry<K,V> {
1870 dl 1.1 K key;
1871     V value;
1872     Entry<K,V> left = null;
1873     Entry<K,V> right = null;
1874     Entry<K,V> parent;
1875     boolean color = BLACK;
1876    
1877     /**
1878     * Make a new cell with given key, value, and parent, and with
1879     * <tt>null</tt> child links, and BLACK color.
1880     */
1881     Entry(K key, V value, Entry<K,V> parent) {
1882     this.key = key;
1883     this.value = value;
1884     this.parent = parent;
1885     }
1886    
1887     /**
1888     * Returns the key.
1889     *
1890 jsr166 1.14 * @return the key
1891 dl 1.1 */
1892     public K getKey() {
1893     return key;
1894     }
1895    
1896     /**
1897     * Returns the value associated with the key.
1898     *
1899 jsr166 1.14 * @return the value associated with the key
1900 dl 1.1 */
1901     public V getValue() {
1902     return value;
1903     }
1904    
1905     /**
1906     * Replaces the value currently associated with the key with the given
1907     * value.
1908     *
1909     * @return the value associated with the key before this method was
1910 jsr166 1.14 * called
1911 dl 1.1 */
1912     public V setValue(V value) {
1913     V oldValue = this.value;
1914     this.value = value;
1915     return oldValue;
1916     }
1917    
1918     public boolean equals(Object o) {
1919     if (!(o instanceof Map.Entry))
1920     return false;
1921 jsr166 1.36 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1922 dl 1.1
1923     return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
1924     }
1925    
1926     public int hashCode() {
1927     int keyHash = (key==null ? 0 : key.hashCode());
1928     int valueHash = (value==null ? 0 : value.hashCode());
1929     return keyHash ^ valueHash;
1930     }
1931    
1932     public String toString() {
1933     return key + "=" + value;
1934     }
1935     }
1936    
1937     /**
1938     * Returns the first Entry in the TreeMap (according to the TreeMap's
1939     * key-sort function). Returns null if the TreeMap is empty.
1940     */
1941 dl 1.29 final Entry<K,V> getFirstEntry() {
1942 dl 1.1 Entry<K,V> p = root;
1943     if (p != null)
1944     while (p.left != null)
1945     p = p.left;
1946     return p;
1947     }
1948    
1949     /**
1950     * Returns the last Entry in the TreeMap (according to the TreeMap's
1951     * key-sort function). Returns null if the TreeMap is empty.
1952     */
1953 dl 1.29 final Entry<K,V> getLastEntry() {
1954 dl 1.1 Entry<K,V> p = root;
1955     if (p != null)
1956     while (p.right != null)
1957     p = p.right;
1958     return p;
1959     }
1960    
1961     /**
1962     * Returns the successor of the specified Entry, or null if no such.
1963     */
1964 dl 1.31 static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
1965 dl 1.1 if (t == null)
1966     return null;
1967     else if (t.right != null) {
1968     Entry<K,V> p = t.right;
1969     while (p.left != null)
1970     p = p.left;
1971     return p;
1972     } else {
1973     Entry<K,V> p = t.parent;
1974     Entry<K,V> ch = t;
1975     while (p != null && ch == p.right) {
1976     ch = p;
1977     p = p.parent;
1978     }
1979     return p;
1980     }
1981     }
1982    
1983     /**
1984     * Returns the predecessor of the specified Entry, or null if no such.
1985     */
1986 dl 1.31 static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {
1987 dl 1.1 if (t == null)
1988     return null;
1989     else if (t.left != null) {
1990     Entry<K,V> p = t.left;
1991     while (p.right != null)
1992     p = p.right;
1993     return p;
1994     } else {
1995     Entry<K,V> p = t.parent;
1996     Entry<K,V> ch = t;
1997     while (p != null && ch == p.left) {
1998     ch = p;
1999     p = p.parent;
2000     }
2001     return p;
2002     }
2003     }
2004    
2005     /**
2006     * Balancing operations.
2007     *
2008     * Implementations of rebalancings during insertion and deletion are
2009     * slightly different than the CLR version. Rather than using dummy
2010     * nilnodes, we use a set of accessors that deal properly with null. They
2011     * are used to avoid messiness surrounding nullness checks in the main
2012     * algorithms.
2013     */
2014    
2015     private static <K,V> boolean colorOf(Entry<K,V> p) {
2016     return (p == null ? BLACK : p.color);
2017     }
2018    
2019     private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) {
2020     return (p == null ? null: p.parent);
2021     }
2022    
2023     private static <K,V> void setColor(Entry<K,V> p, boolean c) {
2024     if (p != null)
2025     p.color = c;
2026     }
2027    
2028     private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) {
2029     return (p == null) ? null: p.left;
2030     }
2031    
2032     private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) {
2033     return (p == null) ? null: p.right;
2034     }
2035    
2036 dl 1.33 /** From CLR */
2037 dl 1.1 private void rotateLeft(Entry<K,V> p) {
2038 dl 1.34 if (p != null) {
2039     Entry<K,V> r = p.right;
2040     p.right = r.left;
2041     if (r.left != null)
2042     r.left.parent = p;
2043     r.parent = p.parent;
2044     if (p.parent == null)
2045     root = r;
2046     else if (p.parent.left == p)
2047     p.parent.left = r;
2048     else
2049     p.parent.right = r;
2050     r.left = p;
2051     p.parent = r;
2052     }
2053 dl 1.1 }
2054    
2055 dl 1.33 /** From CLR */
2056 dl 1.1 private void rotateRight(Entry<K,V> p) {
2057 dl 1.34 if (p != null) {
2058     Entry<K,V> l = p.left;
2059     p.left = l.right;
2060     if (l.right != null) l.right.parent = p;
2061     l.parent = p.parent;
2062     if (p.parent == null)
2063     root = l;
2064     else if (p.parent.right == p)
2065     p.parent.right = l;
2066     else p.parent.left = l;
2067     l.right = p;
2068     p.parent = l;
2069     }
2070 dl 1.1 }
2071    
2072 dl 1.33 /** From CLR */
2073 dl 1.1 private void fixAfterInsertion(Entry<K,V> x) {
2074     x.color = RED;
2075    
2076     while (x != null && x != root && x.parent.color == RED) {
2077     if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
2078     Entry<K,V> y = rightOf(parentOf(parentOf(x)));
2079     if (colorOf(y) == RED) {
2080     setColor(parentOf(x), BLACK);
2081     setColor(y, BLACK);
2082     setColor(parentOf(parentOf(x)), RED);
2083     x = parentOf(parentOf(x));
2084     } else {
2085     if (x == rightOf(parentOf(x))) {
2086     x = parentOf(x);
2087     rotateLeft(x);
2088     }
2089     setColor(parentOf(x), BLACK);
2090     setColor(parentOf(parentOf(x)), RED);
2091 dl 1.34 rotateRight(parentOf(parentOf(x)));
2092 dl 1.1 }
2093     } else {
2094     Entry<K,V> y = leftOf(parentOf(parentOf(x)));
2095     if (colorOf(y) == RED) {
2096     setColor(parentOf(x), BLACK);
2097     setColor(y, BLACK);
2098     setColor(parentOf(parentOf(x)), RED);
2099     x = parentOf(parentOf(x));
2100     } else {
2101     if (x == leftOf(parentOf(x))) {
2102     x = parentOf(x);
2103     rotateRight(x);
2104     }
2105 dl 1.31 setColor(parentOf(x), BLACK);
2106 dl 1.1 setColor(parentOf(parentOf(x)), RED);
2107 dl 1.34 rotateLeft(parentOf(parentOf(x)));
2108 dl 1.1 }
2109     }
2110     }
2111     root.color = BLACK;
2112     }
2113    
2114     /**
2115     * Delete node p, and then rebalance the tree.
2116     */
2117     private void deleteEntry(Entry<K,V> p) {
2118 dl 1.33 modCount++;
2119     size--;
2120 dl 1.1
2121     // If strictly internal, copy successor's element to p and then make p
2122     // point to successor.
2123     if (p.left != null && p.right != null) {
2124     Entry<K,V> s = successor (p);
2125     p.key = s.key;
2126     p.value = s.value;
2127     p = s;
2128     } // p has 2 children
2129    
2130     // Start fixup at replacement node, if it exists.
2131     Entry<K,V> replacement = (p.left != null ? p.left : p.right);
2132    
2133     if (replacement != null) {
2134     // Link replacement to parent
2135     replacement.parent = p.parent;
2136     if (p.parent == null)
2137     root = replacement;
2138     else if (p == p.parent.left)
2139     p.parent.left = replacement;
2140     else
2141     p.parent.right = replacement;
2142    
2143     // Null out links so they are OK to use by fixAfterDeletion.
2144     p.left = p.right = p.parent = null;
2145    
2146     // Fix replacement
2147     if (p.color == BLACK)
2148     fixAfterDeletion(replacement);
2149     } else if (p.parent == null) { // return if we are the only node.
2150     root = null;
2151     } else { // No children. Use self as phantom replacement and unlink.
2152     if (p.color == BLACK)
2153     fixAfterDeletion(p);
2154    
2155     if (p.parent != null) {
2156     if (p == p.parent.left)
2157     p.parent.left = null;
2158     else if (p == p.parent.right)
2159     p.parent.right = null;
2160     p.parent = null;
2161     }
2162     }
2163     }
2164    
2165 dl 1.33 /** From CLR */
2166 dl 1.1 private void fixAfterDeletion(Entry<K,V> x) {
2167     while (x != root && colorOf(x) == BLACK) {
2168     if (x == leftOf(parentOf(x))) {
2169     Entry<K,V> sib = rightOf(parentOf(x));
2170    
2171     if (colorOf(sib) == RED) {
2172     setColor(sib, BLACK);
2173     setColor(parentOf(x), RED);
2174     rotateLeft(parentOf(x));
2175     sib = rightOf(parentOf(x));
2176     }
2177    
2178     if (colorOf(leftOf(sib)) == BLACK &&
2179     colorOf(rightOf(sib)) == BLACK) {
2180 dl 1.31 setColor(sib, RED);
2181 dl 1.1 x = parentOf(x);
2182     } else {
2183     if (colorOf(rightOf(sib)) == BLACK) {
2184     setColor(leftOf(sib), BLACK);
2185     setColor(sib, RED);
2186     rotateRight(sib);
2187     sib = rightOf(parentOf(x));
2188     }
2189     setColor(sib, colorOf(parentOf(x)));
2190     setColor(parentOf(x), BLACK);
2191     setColor(rightOf(sib), BLACK);
2192     rotateLeft(parentOf(x));
2193     x = root;
2194     }
2195     } else { // symmetric
2196     Entry<K,V> sib = leftOf(parentOf(x));
2197    
2198     if (colorOf(sib) == RED) {
2199     setColor(sib, BLACK);
2200     setColor(parentOf(x), RED);
2201     rotateRight(parentOf(x));
2202     sib = leftOf(parentOf(x));
2203     }
2204    
2205     if (colorOf(rightOf(sib)) == BLACK &&
2206     colorOf(leftOf(sib)) == BLACK) {
2207 dl 1.31 setColor(sib, RED);
2208 dl 1.1 x = parentOf(x);
2209     } else {
2210     if (colorOf(leftOf(sib)) == BLACK) {
2211     setColor(rightOf(sib), BLACK);
2212     setColor(sib, RED);
2213     rotateLeft(sib);
2214     sib = leftOf(parentOf(x));
2215     }
2216     setColor(sib, colorOf(parentOf(x)));
2217     setColor(parentOf(x), BLACK);
2218     setColor(leftOf(sib), BLACK);
2219     rotateRight(parentOf(x));
2220     x = root;
2221     }
2222     }
2223     }
2224    
2225     setColor(x, BLACK);
2226     }
2227    
2228     private static final long serialVersionUID = 919286545866124006L;
2229    
2230     /**
2231     * Save the state of the <tt>TreeMap</tt> instance to a stream (i.e.,
2232     * serialize it).
2233     *
2234     * @serialData The <i>size</i> of the TreeMap (the number of key-value
2235     * mappings) is emitted (int), followed by the key (Object)
2236     * and value (Object) for each key-value mapping represented
2237     * by the TreeMap. The key-value mappings are emitted in
2238     * key-order (as determined by the TreeMap's Comparator,
2239     * or by the keys' natural ordering if the TreeMap has no
2240     * Comparator).
2241     */
2242     private void writeObject(java.io.ObjectOutputStream s)
2243     throws java.io.IOException {
2244     // Write out the Comparator and any hidden stuff
2245     s.defaultWriteObject();
2246    
2247     // Write out size (number of Mappings)
2248     s.writeInt(size);
2249    
2250     // Write out keys and values (alternating)
2251 jsr166 1.14 for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
2252 dl 1.1 Map.Entry<K,V> e = i.next();
2253     s.writeObject(e.getKey());
2254     s.writeObject(e.getValue());
2255     }
2256     }
2257    
2258     /**
2259     * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e.,
2260     * deserialize it).
2261     */
2262     private void readObject(final java.io.ObjectInputStream s)
2263     throws java.io.IOException, ClassNotFoundException {
2264     // Read in the Comparator and any hidden stuff
2265     s.defaultReadObject();
2266    
2267     // Read in size
2268     int size = s.readInt();
2269    
2270     buildFromSorted(size, null, s, null);
2271     }
2272    
2273 dl 1.33 /** Intended to be called only from TreeSet.readObject */
2274 dl 1.1 void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2275     throws java.io.IOException, ClassNotFoundException {
2276     buildFromSorted(size, null, s, defaultVal);
2277     }
2278    
2279 dl 1.33 /** Intended to be called only from TreeSet.addAll */
2280 jsr166 1.12 void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2281 dl 1.1 try {
2282     buildFromSorted(set.size(), set.iterator(), null, defaultVal);
2283     } catch (java.io.IOException cannotHappen) {
2284     } catch (ClassNotFoundException cannotHappen) {
2285     }
2286     }
2287    
2288    
2289     /**
2290     * Linear time tree building algorithm from sorted data. Can accept keys
2291     * and/or values from iterator or stream. This leads to too many
2292     * parameters, but seems better than alternatives. The four formats
2293     * that this method accepts are:
2294     *
2295     * 1) An iterator of Map.Entries. (it != null, defaultVal == null).
2296     * 2) An iterator of keys. (it != null, defaultVal != null).
2297     * 3) A stream of alternating serialized keys and values.
2298     * (it == null, defaultVal == null).
2299     * 4) A stream of serialized keys. (it == null, defaultVal != null).
2300     *
2301     * It is assumed that the comparator of the TreeMap is already set prior
2302     * to calling this method.
2303     *
2304     * @param size the number of keys (or key-value pairs) to be read from
2305 jsr166 1.14 * the iterator or stream
2306 dl 1.1 * @param it If non-null, new entries are created from entries
2307     * or keys read from this iterator.
2308     * @param str If non-null, new entries are created from keys and
2309     * possibly values read from this stream in serialized form.
2310     * Exactly one of it and str should be non-null.
2311     * @param defaultVal if non-null, this default value is used for
2312     * each value in the map. If null, each value is read from
2313     * iterator or stream, as described above.
2314     * @throws IOException propagated from stream reads. This cannot
2315     * occur if str is null.
2316     * @throws ClassNotFoundException propagated from readObject.
2317     * This cannot occur if str is null.
2318     */
2319 jsr166 1.27 private void buildFromSorted(int size, Iterator it,
2320     java.io.ObjectInputStream str,
2321     V defaultVal)
2322 dl 1.1 throws java.io.IOException, ClassNotFoundException {
2323     this.size = size;
2324 jsr166 1.27 root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
2325     it, str, defaultVal);
2326 dl 1.1 }
2327    
2328     /**
2329     * Recursive "helper method" that does the real work of the
2330 jsr166 1.27 * previous method. Identically named parameters have
2331 dl 1.1 * identical definitions. Additional parameters are documented below.
2332     * It is assumed that the comparator and size fields of the TreeMap are
2333     * already set prior to calling this method. (It ignores both fields.)
2334     *
2335     * @param level the current level of tree. Initial call should be 0.
2336     * @param lo the first element index of this subtree. Initial should be 0.
2337     * @param hi the last element index of this subtree. Initial should be
2338 jsr166 1.14 * size-1.
2339 dl 1.1 * @param redLevel the level at which nodes should be red.
2340     * Must be equal to computeRedLevel for tree of this size.
2341     */
2342     private final Entry<K,V> buildFromSorted(int level, int lo, int hi,
2343     int redLevel,
2344     Iterator it,
2345     java.io.ObjectInputStream str,
2346     V defaultVal)
2347     throws java.io.IOException, ClassNotFoundException {
2348     /*
2349     * Strategy: The root is the middlemost element. To get to it, we
2350     * have to first recursively construct the entire left subtree,
2351     * so as to grab all of its elements. We can then proceed with right
2352     * subtree.
2353     *
2354     * The lo and hi arguments are the minimum and maximum
2355     * indices to pull out of the iterator or stream for current subtree.
2356     * They are not actually indexed, we just proceed sequentially,
2357     * ensuring that items are extracted in corresponding order.
2358     */
2359    
2360     if (hi < lo) return null;
2361    
2362 dl 1.40 int mid = (lo + hi) >>> 1;
2363 dl 1.1
2364     Entry<K,V> left = null;
2365     if (lo < mid)
2366     left = buildFromSorted(level+1, lo, mid - 1, redLevel,
2367     it, str, defaultVal);
2368    
2369     // extract key and/or value from iterator or stream
2370     K key;
2371     V value;
2372     if (it != null) {
2373     if (defaultVal==null) {
2374     Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
2375     key = entry.getKey();
2376     value = entry.getValue();
2377     } else {
2378     key = (K)it.next();
2379     value = defaultVal;
2380     }
2381     } else { // use stream
2382     key = (K) str.readObject();
2383     value = (defaultVal != null ? defaultVal : (V) str.readObject());
2384     }
2385    
2386     Entry<K,V> middle = new Entry<K,V>(key, value, null);
2387    
2388     // color nodes in non-full bottommost level red
2389     if (level == redLevel)
2390     middle.color = RED;
2391    
2392     if (left != null) {
2393     middle.left = left;
2394     left.parent = middle;
2395     }
2396    
2397     if (mid < hi) {
2398     Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
2399     it, str, defaultVal);
2400     middle.right = right;
2401     right.parent = middle;
2402     }
2403    
2404     return middle;
2405     }
2406    
2407     /**
2408     * Find the level down to which to assign all nodes BLACK. This is the
2409     * last `full' level of the complete binary tree produced by
2410     * buildTree. The remaining nodes are colored RED. (This makes a `nice'
2411     * set of color assignments wrt future insertions.) This level number is
2412     * computed by finding the number of splits needed to reach the zeroeth
2413     * node. (The answer is ~lg(N), but in any case must be computed by same
2414     * quick O(lg(N)) loop.)
2415     */
2416     private static int computeRedLevel(int sz) {
2417     int level = 0;
2418     for (int m = sz - 1; m >= 0; m = m / 2 - 1)
2419     level++;
2420     return level;
2421     }
2422     }