ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.34
Committed: Sun Apr 23 20:59:49 2006 UTC (18 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.33: +87 -126 lines
Log Message:
Small coding improvements

File Contents

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