ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.31
Committed: Fri Apr 21 13:42:57 2006 UTC (18 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.30: +126 -114 lines
Log Message:
Catch illegal submaps; performance tweaks

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