ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.45
Committed: Sun May 18 23:47:56 2008 UTC (16 years ago) by jsr166
Branch: MAIN
Changes since 1.44: +44 -44 lines
Log Message:
Sync with OpenJDK; untabify

File Contents

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