ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.22
Committed: Fri Jun 24 20:44:49 2005 UTC (18 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.21: +29 -0 lines
Log Message:
@since 1.6

File Contents

# User Rev Content
1 dl 1.1 /*
2     * %W% %E%
3     *
4 jsr166 1.10 * Copyright 2005 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 jsr166 1.19 import java.util.*; // for javadoc (till 6280605 is fixed)
10 dl 1.1
11     /**
12 jsr166 1.14 * A Red-Black tree based {@link NavigableMap} implementation.
13     * The map is sorted according to the {@linkplain Comparable natural
14     * ordering} of its keys, or by a {@link Comparator} provided at map
15     * creation time, depending on which constructor is used.
16 dl 1.1 *
17 jsr166 1.14 * <p>This implementation provides guaranteed log(n) time cost for the
18 dl 1.1 * <tt>containsKey</tt>, <tt>get</tt>, <tt>put</tt> and <tt>remove</tt>
19     * operations. Algorithms are adaptations of those in Cormen, Leiserson, and
20 jsr166 1.14 * Rivest's <I>Introduction to Algorithms</I>.
21 dl 1.1 *
22 jsr166 1.14 * <p>Note that the ordering maintained by a sorted map (whether or not an
23 dl 1.1 * explicit comparator is provided) must be <i>consistent with equals</i> if
24     * this sorted map is to correctly implement the <tt>Map</tt> interface. (See
25     * <tt>Comparable</tt> or <tt>Comparator</tt> for a precise definition of
26     * <i>consistent with equals</i>.) This is so because the <tt>Map</tt>
27     * interface is defined in terms of the equals operation, but a map performs
28     * all key comparisons using its <tt>compareTo</tt> (or <tt>compare</tt>)
29     * method, so two keys that are deemed equal by this method are, from the
30     * standpoint of the sorted map, equal. The behavior of a sorted map
31     * <i>is</i> well-defined even if its ordering is inconsistent with equals; it
32 jsr166 1.14 * just fails to obey the general contract of the <tt>Map</tt> interface.
33 dl 1.1 *
34 jsr166 1.14 * <p><b>Note that this implementation is not synchronized.</b> If multiple
35 dl 1.1 * threads access a map concurrently, and at least one of the threads modifies
36     * the map structurally, it <i>must</i> be synchronized externally. (A
37     * structural modification is any operation that adds or deletes one or more
38     * mappings; merely changing the value associated with an existing key is not
39     * a structural modification.) This is typically accomplished by
40     * synchronizing on some object that naturally encapsulates the map. If no
41     * such object exists, the map should be "wrapped" using the
42     * <tt>Collections.synchronizedMap</tt> method. This is best done at creation
43     * time, to prevent accidental unsynchronized access to the map:
44     * <pre>
45     * Map m = Collections.synchronizedMap(new TreeMap(...));
46 jsr166 1.14 * </pre>
47 dl 1.1 *
48 jsr166 1.14 * <p>The iterators returned by the <tt>iterator</tt> method of the collections
49     * returned by all of this class's "collection view methods" are
50 dl 1.1 * <i>fail-fast</i>: if the map is structurally modified at any time after the
51     * iterator is created, in any way except through the iterator's own
52 jsr166 1.14 * <tt>remove</tt> method, the iterator will throw a {@link
53     * ConcurrentModificationException}. Thus, in the face of concurrent
54 dl 1.1 * modification, the iterator fails quickly and cleanly, rather than risking
55 jsr166 1.14 * arbitrary, non-deterministic behavior at an undetermined time in the future.
56 dl 1.1 *
57     * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
58     * as it is, generally speaking, impossible to make any hard guarantees in the
59     * presence of unsynchronized concurrent modification. Fail-fast iterators
60     * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
61     * Therefore, it would be wrong to write a program that depended on this
62     * exception for its correctness: <i>the fail-fast behavior of iterators
63 dl 1.5 * should be used only to detect bugs.</i>
64 dl 1.1 *
65     * <p>All <tt>Map.Entry</tt> pairs returned by methods in this class
66     * and its views represent snapshots of mappings at the time they were
67     * produced. They do <em>not</em> support the <tt>Entry.setValue</tt>
68     * method. (Note however that it is possible to change mappings in the
69     * associated map using <tt>put</tt>.)
70     *
71     * <p>This class is a member of the
72     * <a href="{@docRoot}/../guide/collections/index.html">
73     * Java Collections Framework</a>.
74     *
75 jsr166 1.14 * @param <K> the type of keys maintained by this map
76     * @param <V> the type of mapped values
77     *
78 dl 1.1 * @author Josh Bloch and Doug Lea
79     * @version %I%, %G%
80     * @see Map
81     * @see HashMap
82     * @see Hashtable
83     * @see Comparable
84     * @see Comparator
85     * @see Collection
86     * @see Collections#synchronizedMap(Map)
87     * @since 1.2
88     */
89    
90     public class TreeMap<K,V>
91     extends AbstractMap<K,V>
92     implements NavigableMap<K,V>, Cloneable, java.io.Serializable
93     {
94     /**
95 jsr166 1.14 * The comparator used to maintain order in this tree map, or
96     * null if it uses the natural ordering of its keys.
97 dl 1.1 *
98     * @serial
99     */
100     private Comparator<? super K> comparator = null;
101    
102     private transient Entry<K,V> root = null;
103    
104     /**
105     * The number of entries in the tree
106     */
107     private transient int size = 0;
108    
109     /**
110     * The number of structural modifications to the tree.
111     */
112     private transient int modCount = 0;
113    
114     private void incrementSize() { modCount++; size++; }
115     private void decrementSize() { modCount++; size--; }
116    
117     /**
118 jsr166 1.14 * Constructs a new, empty tree map, using the natural ordering of its
119     * keys. All keys inserted into the map must implement the {@link
120     * Comparable} interface. Furthermore, all such keys must be
121     * <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw
122     * a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and
123     * <tt>k2</tt> in the map. If the user attempts to put a key into the
124     * map that violates this constraint (for example, the user attempts to
125     * put a string key into a map whose keys are integers), the
126     * <tt>put(Object key, Object value)</tt> call will throw a
127     * <tt>ClassCastException</tt>.
128 dl 1.1 */
129     public TreeMap() {
130     }
131    
132     /**
133 jsr166 1.14 * Constructs a new, empty tree map, ordered according to the given
134     * comparator. All keys inserted into the map must be <i>mutually
135     * comparable</i> by the given comparator: <tt>comparator.compare(k1,
136     * k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys
137     * <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts to put
138     * a key into the map that violates this constraint, the <tt>put(Object
139     * key, Object value)</tt> call will throw a
140     * <tt>ClassCastException</tt>.
141     *
142     * @param comparator the comparator that will be used to order this map.
143     * If <tt>null</tt>, the {@linkplain Comparable natural
144     * ordering} of the keys will be used.
145     */
146     public TreeMap(Comparator<? super K> comparator) {
147     this.comparator = comparator;
148 dl 1.1 }
149    
150     /**
151 jsr166 1.14 * Constructs a new tree map containing the same mappings as the given
152     * map, ordered according to the <i>natural ordering</i> of its keys.
153     * All keys inserted into the new map must implement the {@link
154     * Comparable} interface. Furthermore, all such keys must be
155     * <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw
156     * a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and
157     * <tt>k2</tt> in the map. This method runs in n*log(n) time.
158     *
159     * @param m the map whose mappings are to be placed in this map
160     * @throws ClassCastException if the keys in m are not {@link Comparable},
161     * or are not mutually comparable
162     * @throws NullPointerException if the specified map is null
163 dl 1.1 */
164     public TreeMap(Map<? extends K, ? extends V> m) {
165     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     : valueSearchNonNull(root, value)));
232     }
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     (n.right != null && valueSearchNull(n.right));
241     }
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     (n.right != null && valueSearchNonNull(n.right, value));
251     }
252    
253     /**
254 jsr166 1.14 * Returns the value to which this map maps the specified key, or
255     * <tt>null</tt> if the map contains no mapping for the key. A return
256 dl 1.1 * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
257     * map contains no mapping for the key; it's also possible that the map
258 jsr166 1.21 * explicitly maps the key to <tt>null</tt>. The {@link #containsKey
259     * containsKey} operation may be used to distinguish these two cases.
260 dl 1.1 *
261 jsr166 1.14 * @param key key whose associated value is to be returned
262 dl 1.1 * @return the value to which this map maps the specified key, or
263 jsr166 1.14 * <tt>null</tt> if the map contains no mapping for the key
264     * @throws ClassCastException if the specified key cannot be compared
265     * with the keys currently in the map
266     * @throws NullPointerException if the specified key is null
267     * and this map uses natural ordering, or its comparator
268     * does not permit null keys
269 dl 1.1 */
270     public V get(Object key) {
271     Entry<K,V> p = getEntry(key);
272     return (p==null ? null : p.value);
273     }
274    
275     public Comparator<? super K> comparator() {
276     return comparator;
277     }
278    
279     /**
280 jsr166 1.14 * @throws NoSuchElementException {@inheritDoc}
281 dl 1.1 */
282     public K firstKey() {
283     return key(getFirstEntry());
284     }
285    
286     /**
287 jsr166 1.14 * @throws NoSuchElementException {@inheritDoc}
288 dl 1.1 */
289     public K lastKey() {
290     return key(getLastEntry());
291     }
292    
293     /**
294 jsr166 1.14 * Copies all of the mappings from the specified map to this map.
295     * These mappings replace any mappings that this map had for any
296     * of the keys currently in the specified map.
297     *
298     * @param map mappings to be stored in this map
299     * @throws ClassCastException if the class of a key or value in
300     * the specified map prevents it from being stored in this map
301     * @throws NullPointerException if the specified map is null or
302     * the specified map contains a null key and this map does not
303     * permit null keys
304 dl 1.1 */
305     public void putAll(Map<? extends K, ? extends V> map) {
306     int mapSize = map.size();
307     if (size==0 && mapSize!=0 && map instanceof SortedMap) {
308     Comparator c = ((SortedMap)map).comparator();
309     if (c == comparator || (c != null && c.equals(comparator))) {
310     ++modCount;
311     try {
312     buildFromSorted(mapSize, map.entrySet().iterator(),
313     null, null);
314     } catch (java.io.IOException cannotHappen) {
315     } catch (ClassNotFoundException cannotHappen) {
316     }
317     return;
318     }
319     }
320     super.putAll(map);
321     }
322    
323     /**
324     * Returns this map's entry for the given key, or <tt>null</tt> if the map
325     * does not contain an entry for the key.
326     *
327     * @return this map's entry for the given key, or <tt>null</tt> if the map
328 jsr166 1.14 * does not contain an entry for the key
329     * @throws ClassCastException if the specified key cannot be compared
330     * with the keys currently in the map
331     * @throws NullPointerException if the specified key is null
332     * and this map uses natural ordering, or its comparator
333     * does not permit null keys
334 dl 1.1 */
335     private Entry<K,V> getEntry(Object key) {
336     // Offload comparator-based version for sake of performance
337     if (comparator != null)
338     return getEntryUsingComparator(key);
339 jsr166 1.12 Comparable<? super K> k = (Comparable<? super K>) key;
340 dl 1.1 Entry<K,V> p = root;
341     while (p != null) {
342     int cmp = k.compareTo(p.key);
343     if (cmp < 0)
344     p = p.left;
345     else if (cmp > 0)
346     p = p.right;
347     else
348     return p;
349     }
350     return null;
351     }
352    
353     /**
354     * Version of getEntry using comparator. Split off from getEntry
355     * for performance. (This is not worth doing for most methods,
356     * that are less dependent on comparator performance, but is
357     * worthwhile here.)
358     */
359     private Entry<K,V> getEntryUsingComparator(Object key) {
360     K k = (K) key;
361     Comparator<? super K> cpr = comparator;
362     Entry<K,V> p = root;
363     while (p != null) {
364     int cmp = cpr.compare(k, p.key);
365     if (cmp < 0)
366     p = p.left;
367     else if (cmp > 0)
368     p = p.right;
369     else
370     return p;
371     }
372     return null;
373     }
374    
375     /**
376     * Gets the entry corresponding to the specified key; if no such entry
377     * exists, returns the entry for the least key greater than the specified
378     * key; if no such entry exists (i.e., the greatest key in the Tree is less
379     * than the specified key), returns <tt>null</tt>.
380     */
381     private Entry<K,V> getCeilingEntry(K key) {
382     Entry<K,V> p = root;
383     if (p==null)
384     return null;
385    
386     while (true) {
387     int cmp = compare(key, p.key);
388     if (cmp < 0) {
389     if (p.left != null)
390     p = p.left;
391     else
392     return p;
393     } else if (cmp > 0) {
394     if (p.right != null) {
395     p = p.right;
396     } else {
397     Entry<K,V> parent = p.parent;
398     Entry<K,V> ch = p;
399     while (parent != null && ch == parent.right) {
400     ch = parent;
401     parent = parent.parent;
402     }
403     return parent;
404     }
405     } else
406     return p;
407     }
408     }
409    
410     /**
411     * Gets the entry corresponding to the specified key; if no such entry
412     * exists, returns the entry for the greatest key less than the specified
413     * key; if no such entry exists, returns <tt>null</tt>.
414     */
415     private Entry<K,V> getFloorEntry(K key) {
416     Entry<K,V> p = root;
417     if (p==null)
418     return null;
419    
420     while (true) {
421     int cmp = compare(key, p.key);
422     if (cmp > 0) {
423     if (p.right != null)
424     p = p.right;
425     else
426     return p;
427     } else if (cmp < 0) {
428     if (p.left != null) {
429     p = p.left;
430     } else {
431     Entry<K,V> parent = p.parent;
432     Entry<K,V> ch = p;
433     while (parent != null && ch == parent.left) {
434     ch = parent;
435     parent = parent.parent;
436     }
437     return parent;
438     }
439     } else
440     return p;
441    
442     }
443     }
444    
445     /**
446     * Gets the entry for the least key greater than the specified
447     * key; if no such entry exists, returns the entry for the least
448     * key greater than the specified key; if no such entry exists
449     * returns <tt>null</tt>.
450     */
451     private Entry<K,V> getHigherEntry(K key) {
452     Entry<K,V> p = root;
453     if (p==null)
454     return null;
455    
456     while (true) {
457     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     }
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     private Entry<K,V> getLowerEntry(K key) {
485     Entry<K,V> p = root;
486     if (p==null)
487     return null;
488    
489     while (true) {
490     int cmp = compare(key, p.key);
491     if (cmp > 0) {
492     if (p.right != null)
493     p = p.right;
494     else
495     return p;
496     } else {
497     if (p.left != null) {
498     p = p.left;
499     } else {
500     Entry<K,V> parent = p.parent;
501     Entry<K,V> ch = p;
502     while (parent != null && ch == parent.left) {
503     ch = parent;
504     parent = parent.parent;
505     }
506     return parent;
507     }
508     }
509     }
510     }
511    
512     /**
513 jsr166 1.14 * Returns the key corresponding to the specified Entry.
514     * @throws NoSuchElementException if the Entry is null
515 dl 1.1 */
516     private static <K> K key(Entry<K,?> e) {
517     if (e==null)
518     throw new NoSuchElementException();
519     return e.key;
520     }
521    
522     /**
523     * Associates the specified value with the specified key in this map.
524 jsr166 1.20 * If the map previously contained a mapping for the key, the old
525 dl 1.1 * value is replaced.
526     *
527 jsr166 1.14 * @param key key with which the specified value is to be associated
528     * @param value value to be associated with the specified key
529 dl 1.1 *
530 jsr166 1.14 * @return the previous value associated with <tt>key</tt>, or
531     * <tt>null</tt> if there was no mapping for <tt>key</tt>.
532     * (A <tt>null</tt> return can also indicate that the map
533     * previously associated <tt>null</tt> with <tt>key</tt>.)
534     * @throws ClassCastException if the specified key cannot be compared
535     * with the keys currently in the map
536     * @throws NullPointerException if the specified key is null
537     * and this map uses natural ordering, or its comparator
538     * does not permit null keys
539 dl 1.1 */
540     public V put(K key, V value) {
541     Entry<K,V> t = root;
542    
543     if (t == null) {
544 dl 1.13 if (key == null) {
545     if (comparator == null)
546     throw new NullPointerException();
547     comparator.compare(key, key);
548     }
549 dl 1.1 incrementSize();
550     root = new Entry<K,V>(key, value, null);
551     return null;
552 dl 1.8 }
553 dl 1.1
554     while (true) {
555     int cmp = compare(key, t.key);
556     if (cmp == 0) {
557     return t.setValue(value);
558     } else if (cmp < 0) {
559     if (t.left != null) {
560     t = t.left;
561     } else {
562     incrementSize();
563     t.left = new Entry<K,V>(key, value, t);
564     fixAfterInsertion(t.left);
565     return null;
566     }
567     } else { // cmp > 0
568     if (t.right != null) {
569     t = t.right;
570     } else {
571     incrementSize();
572     t.right = new Entry<K,V>(key, value, t);
573     fixAfterInsertion(t.right);
574     return null;
575     }
576     }
577     }
578     }
579    
580     /**
581     * Removes the mapping for this key from this TreeMap if present.
582     *
583     * @param key key for which mapping should be removed
584 jsr166 1.14 * @return the previous value associated with <tt>key</tt>, or
585     * <tt>null</tt> if there was no mapping for <tt>key</tt>.
586     * (A <tt>null</tt> return can also indicate that the map
587     * previously associated <tt>null</tt> with <tt>key</tt>.)
588     * @throws ClassCastException if the specified key cannot be compared
589     * with the keys currently in the map
590     * @throws NullPointerException if the specified key is null
591     * and this map uses natural ordering, or its comparator
592     * does not permit null keys
593 dl 1.1 */
594     public V remove(Object key) {
595     Entry<K,V> p = getEntry(key);
596     if (p == null)
597     return null;
598    
599     V oldValue = p.value;
600     deleteEntry(p);
601     return oldValue;
602     }
603    
604     /**
605 jsr166 1.14 * Removes all of the mappings from this map.
606     * The map will be empty after this call returns.
607 dl 1.1 */
608     public void clear() {
609     modCount++;
610     size = 0;
611     root = null;
612     }
613    
614     /**
615     * Returns a shallow copy of this <tt>TreeMap</tt> instance. (The keys and
616     * values themselves are not cloned.)
617     *
618 jsr166 1.14 * @return a shallow copy of this map
619 dl 1.1 */
620     public Object clone() {
621     TreeMap<K,V> clone = null;
622     try {
623     clone = (TreeMap<K,V>) super.clone();
624     } catch (CloneNotSupportedException e) {
625     throw new InternalError();
626     }
627    
628     // Put clone into "virgin" state (except for comparator)
629     clone.root = null;
630     clone.size = 0;
631     clone.modCount = 0;
632     clone.entrySet = null;
633     clone.descendingEntrySet = null;
634     clone.descendingKeySet = null;
635    
636     // Initialize clone with our mappings
637     try {
638     clone.buildFromSorted(size, entrySet().iterator(), null, null);
639     } catch (java.io.IOException cannotHappen) {
640     } catch (ClassNotFoundException cannotHappen) {
641     }
642    
643     return clone;
644     }
645    
646     // NavigableMap API methods
647    
648 jsr166 1.22 /**
649     * @since 1.6
650     */
651 dl 1.1 public Map.Entry<K,V> firstEntry() {
652     Entry<K,V> e = getFirstEntry();
653 dl 1.16 return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
654 dl 1.1 }
655    
656 jsr166 1.22 /**
657     * @since 1.6
658     */
659 dl 1.1 public Map.Entry<K,V> lastEntry() {
660     Entry<K,V> e = getLastEntry();
661 dl 1.16 return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
662 dl 1.1 }
663    
664 jsr166 1.22 /**
665     * @since 1.6
666     */
667 dl 1.1 public Map.Entry<K,V> pollFirstEntry() {
668     Entry<K,V> p = getFirstEntry();
669 dl 1.8 if (p == null)
670 dl 1.1 return null;
671 dl 1.16 Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(p);
672 dl 1.1 deleteEntry(p);
673     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.8 if (p == null)
682 dl 1.1 return null;
683 dl 1.16 Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(p);
684 dl 1.1 deleteEntry(p);
685     return result;
686     }
687    
688     /**
689 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
690     * @throws NullPointerException if the specified key is null
691     * and this map uses natural ordering, or its comparator
692     * does not permit null keys
693 jsr166 1.22 * @since 1.6
694 dl 1.1 */
695 jsr166 1.14 public Map.Entry<K,V> lowerEntry(K key) {
696     Entry<K,V> e = getLowerEntry(key);
697 dl 1.16 return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
698 dl 1.1 }
699    
700     /**
701 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
702     * @throws NullPointerException if the specified key is null
703     * and this map uses natural ordering, or its comparator
704     * does not permit null keys
705 jsr166 1.22 * @since 1.6
706 dl 1.1 */
707 jsr166 1.14 public K lowerKey(K key) {
708     Entry<K,V> e = getLowerEntry(key);
709 dl 1.1 return (e == null)? null : e.key;
710     }
711    
712     /**
713 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
714     * @throws NullPointerException if the specified key is null
715     * and this map uses natural ordering, or its comparator
716     * does not permit null keys
717 jsr166 1.22 * @since 1.6
718 dl 1.1 */
719     public Map.Entry<K,V> floorEntry(K key) {
720     Entry<K,V> e = getFloorEntry(key);
721 dl 1.16 return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
722 dl 1.1 }
723    
724     /**
725 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
726     * @throws NullPointerException if the specified key is null
727     * and this map uses natural ordering, or its comparator
728     * does not permit null keys
729 jsr166 1.22 * @since 1.6
730 dl 1.1 */
731     public K floorKey(K key) {
732     Entry<K,V> e = getFloorEntry(key);
733     return (e == null)? null : e.key;
734     }
735    
736     /**
737 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
738     * @throws NullPointerException if the specified key is null
739     * and this map uses natural ordering, or its comparator
740     * does not permit null keys
741 jsr166 1.22 * @since 1.6
742 dl 1.1 */
743 jsr166 1.14 public Map.Entry<K,V> ceilingEntry(K key) {
744     Entry<K,V> e = getCeilingEntry(key);
745 dl 1.16 return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
746 dl 1.1 }
747    
748     /**
749 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
750     * @throws NullPointerException if the specified key is null
751     * and this map uses natural ordering, or its comparator
752     * does not permit null keys
753 jsr166 1.22 * @since 1.6
754 dl 1.1 */
755 jsr166 1.14 public K ceilingKey(K key) {
756     Entry<K,V> e = getCeilingEntry(key);
757 dl 1.1 return (e == null)? null : e.key;
758     }
759    
760     /**
761 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
762     * @throws NullPointerException if the specified key is null
763     * and this map uses natural ordering, or its comparator
764     * does not permit null keys
765 jsr166 1.22 * @since 1.6
766 dl 1.1 */
767 jsr166 1.14 public Map.Entry<K,V> higherEntry(K key) {
768     Entry<K,V> e = getHigherEntry(key);
769 dl 1.16 return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
770 dl 1.1 }
771    
772     /**
773 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
774     * @throws NullPointerException if the specified key is null
775     * and this map uses natural ordering, or its comparator
776     * does not permit null keys
777 jsr166 1.22 * @since 1.6
778 dl 1.1 */
779 jsr166 1.14 public K higherKey(K key) {
780     Entry<K,V> e = getHigherEntry(key);
781 dl 1.1 return (e == null)? null : e.key;
782     }
783    
784     // Views
785    
786     /**
787     * Fields initialized to contain an instance of the entry set view
788     * the first time this view is requested. Views are stateless, so
789     * there's no reason to create more than one.
790     */
791     private transient Set<Map.Entry<K,V>> entrySet = null;
792     private transient Set<Map.Entry<K,V>> descendingEntrySet = null;
793 dl 1.8 private transient Set<K> descendingKeySet = null;
794 dl 1.1
795     /**
796 jsr166 1.14 * Returns a {@link Set} view of the keys contained in this map.
797     * The set's iterator returns the keys in ascending order.
798     * The set is backed by the map, so changes to the map are
799     * reflected in the set, and vice-versa. If the map is modified
800     * while an iteration over the set is in progress (except through
801     * the iterator's own <tt>remove</tt> operation), the results of
802     * the iteration are undefined. The set supports element removal,
803     * which removes the corresponding mapping from the map, via the
804     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
805 jsr166 1.15 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
806     * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
807 jsr166 1.14 * operations.
808 dl 1.1 */
809     public Set<K> keySet() {
810     Set<K> ks = keySet;
811     return (ks != null) ? ks : (keySet = new KeySet());
812     }
813    
814     class KeySet extends AbstractSet<K> {
815     public Iterator<K> iterator() {
816     return new KeyIterator(getFirstEntry());
817     }
818 dl 1.8
819 dl 1.1 public int size() {
820     return TreeMap.this.size();
821     }
822 dl 1.8
823 dl 1.1 public boolean contains(Object o) {
824     return containsKey(o);
825     }
826 dl 1.8
827 dl 1.1 public boolean remove(Object o) {
828     int oldSize = size;
829     TreeMap.this.remove(o);
830     return size != oldSize;
831     }
832 dl 1.8
833 dl 1.1 public void clear() {
834     TreeMap.this.clear();
835     }
836     }
837    
838     /**
839 jsr166 1.14 * Returns a {@link Collection} view of the values contained in this map.
840     * The collection's iterator returns the values in ascending order
841     * of the corresponding keys.
842     * The collection is backed by the map, so changes to the map are
843     * reflected in the collection, and vice-versa. If the map is
844     * modified while an iteration over the collection is in progress
845     * (except through the iterator's own <tt>remove</tt> operation),
846     * the results of the iteration are undefined. The collection
847     * supports element removal, which removes the corresponding
848     * mapping from the map, via the <tt>Iterator.remove</tt>,
849     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
850     * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
851 jsr166 1.15 * support the <tt>add</tt> or <tt>addAll</tt> operations.
852 dl 1.1 */
853     public Collection<V> values() {
854     Collection<V> vs = values;
855     return (vs != null) ? vs : (values = new Values());
856     }
857    
858     class Values extends AbstractCollection<V> {
859     public Iterator<V> iterator() {
860     return new ValueIterator(getFirstEntry());
861     }
862 dl 1.8
863 dl 1.1 public int size() {
864     return TreeMap.this.size();
865     }
866 dl 1.8
867 dl 1.1 public boolean contains(Object o) {
868     for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
869     if (valEquals(e.getValue(), o))
870     return true;
871     return false;
872     }
873 dl 1.8
874 dl 1.1 public boolean remove(Object o) {
875     for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
876     if (valEquals(e.getValue(), o)) {
877     deleteEntry(e);
878     return true;
879     }
880     }
881     return false;
882     }
883 dl 1.8
884 dl 1.1 public void clear() {
885     TreeMap.this.clear();
886     }
887     }
888    
889     /**
890 jsr166 1.14 * Returns a {@link Set} view of the mappings contained in this map.
891     * The set's iterator returns the entries in ascending key order.
892     * The set is backed by the map, so changes to the map are
893     * reflected in the set, and vice-versa. If the map is modified
894     * while an iteration over the set is in progress (except through
895     * the iterator's own <tt>remove</tt> operation, or through the
896     * <tt>setValue</tt> operation on a map entry returned by the
897     * iterator) the results of the iteration are undefined. The set
898     * supports element removal, which removes the corresponding
899     * mapping from the map, via the <tt>Iterator.remove</tt>,
900 dl 1.1 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
901 jsr166 1.14 * <tt>clear</tt> operations. It does not support the
902     * <tt>add</tt> or <tt>addAll</tt> operations.
903 dl 1.1 */
904     public Set<Map.Entry<K,V>> entrySet() {
905     Set<Map.Entry<K,V>> es = entrySet;
906     return (es != null) ? es : (entrySet = new EntrySet());
907     }
908    
909     class EntrySet extends AbstractSet<Map.Entry<K,V>> {
910     public Iterator<Map.Entry<K,V>> iterator() {
911     return new EntryIterator(getFirstEntry());
912     }
913 dl 1.8
914 dl 1.1 public boolean contains(Object o) {
915     if (!(o instanceof Map.Entry))
916     return false;
917     Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
918     V value = entry.getValue();
919     Entry<K,V> p = getEntry(entry.getKey());
920     return p != null && valEquals(p.getValue(), value);
921     }
922 dl 1.8
923 dl 1.1 public boolean remove(Object o) {
924     if (!(o instanceof Map.Entry))
925     return false;
926     Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
927     V value = entry.getValue();
928     Entry<K,V> p = getEntry(entry.getKey());
929     if (p != null && valEquals(p.getValue(), value)) {
930     deleteEntry(p);
931     return true;
932     }
933     return false;
934     }
935 dl 1.8
936 dl 1.1 public int size() {
937     return TreeMap.this.size();
938     }
939 dl 1.8
940 dl 1.1 public void clear() {
941     TreeMap.this.clear();
942     }
943     }
944    
945 jsr166 1.22 /**
946     * @since 1.6
947     */
948 dl 1.1 public Set<Map.Entry<K,V>> descendingEntrySet() {
949     Set<Map.Entry<K,V>> es = descendingEntrySet;
950     return (es != null) ? es : (descendingEntrySet = new DescendingEntrySet());
951     }
952    
953     class DescendingEntrySet extends EntrySet {
954     public Iterator<Map.Entry<K,V>> iterator() {
955     return new DescendingEntryIterator(getLastEntry());
956     }
957     }
958    
959 jsr166 1.22 /**
960     * @since 1.6
961     */
962 dl 1.1 public Set<K> descendingKeySet() {
963     Set<K> ks = descendingKeySet;
964     return (ks != null) ? ks : (descendingKeySet = new DescendingKeySet());
965     }
966    
967     class DescendingKeySet extends KeySet {
968     public Iterator<K> iterator() {
969     return new DescendingKeyIterator(getLastEntry());
970     }
971     }
972    
973     /**
974 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
975 dl 1.1 * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
976 jsr166 1.14 * null and this map uses natural ordering, or its comparator
977     * does not permit null keys
978     * @throws IllegalArgumentException {@inheritDoc}
979 jsr166 1.22 * @since 1.6
980 dl 1.1 */
981 dl 1.4 public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
982 dl 1.1 return new SubMap(fromKey, toKey);
983     }
984    
985     /**
986 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
987     * @throws NullPointerException if <tt>toKey</tt> is null
988     * and this map uses natural ordering, or its comparator
989     * does not permit null keys
990     * @throws IllegalArgumentException {@inheritDoc}
991 jsr166 1.22 * @since 1.6
992 dl 1.1 */
993 dl 1.4 public NavigableMap<K,V> navigableHeadMap(K toKey) {
994 dl 1.1 return new SubMap(toKey, true);
995     }
996    
997     /**
998 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
999     * @throws NullPointerException if <tt>fromKey</tt> is null
1000     * and this map uses natural ordering, or its comparator
1001     * does not permit null keys
1002     * @throws IllegalArgumentException {@inheritDoc}
1003 jsr166 1.22 * @since 1.6
1004 dl 1.1 */
1005 dl 1.4 public NavigableMap<K,V> navigableTailMap(K fromKey) {
1006     return new SubMap(fromKey, false);
1007     }
1008    
1009     /**
1010 jsr166 1.14 * Equivalent to {@link #navigableSubMap} but with a return type
1011     * conforming to the <tt>SortedMap</tt> interface.
1012     *
1013     * <p>{@inheritDoc}
1014     *
1015     * @throws ClassCastException {@inheritDoc}
1016 dl 1.4 * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
1017 jsr166 1.14 * null and this map uses natural ordering, or its comparator
1018     * does not permit null keys
1019     * @throws IllegalArgumentException {@inheritDoc}
1020 dl 1.4 */
1021     public SortedMap<K,V> subMap(K fromKey, K toKey) {
1022     return new SubMap(fromKey, toKey);
1023     }
1024    
1025     /**
1026 jsr166 1.14 * Equivalent to {@link #navigableHeadMap} but with a return type
1027     * conforming to the <tt>SortedMap</tt> interface.
1028     *
1029     * <p>{@inheritDoc}
1030 dl 1.4 *
1031 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
1032     * @throws NullPointerException if <tt>toKey</tt> is null
1033     * and this map uses natural ordering, or its comparator
1034     * does not permit null keys
1035     * @throws IllegalArgumentException {@inheritDoc}
1036 dl 1.4 */
1037     public SortedMap<K,V> headMap(K toKey) {
1038     return new SubMap(toKey, true);
1039     }
1040    
1041     /**
1042 jsr166 1.14 * Equivalent to {@link #navigableTailMap} but with a return type
1043     * conforming to the <tt>SortedMap</tt> interface.
1044     *
1045     * <p>{@inheritDoc}
1046 dl 1.4 *
1047 jsr166 1.14 * @throws ClassCastException {@inheritDoc}
1048     * @throws NullPointerException if <tt>fromKey</tt> is null
1049     * and this map uses natural ordering, or its comparator
1050     * does not permit null keys
1051     * @throws IllegalArgumentException {@inheritDoc}
1052 dl 1.4 */
1053     public SortedMap<K,V> tailMap(K fromKey) {
1054 dl 1.1 return new SubMap(fromKey, false);
1055     }
1056    
1057     private class SubMap
1058     extends AbstractMap<K,V>
1059     implements NavigableMap<K,V>, java.io.Serializable {
1060     private static final long serialVersionUID = -6520786458950516097L;
1061    
1062     /**
1063     * fromKey is significant only if fromStart is false. Similarly,
1064     * toKey is significant only if toStart is false.
1065     */
1066     private boolean fromStart = false, toEnd = false;
1067     private K fromKey, toKey;
1068    
1069     SubMap(K fromKey, K toKey) {
1070     if (compare(fromKey, toKey) > 0)
1071     throw new IllegalArgumentException("fromKey > toKey");
1072     this.fromKey = fromKey;
1073     this.toKey = toKey;
1074     }
1075    
1076     SubMap(K key, boolean headMap) {
1077     compare(key, key); // Type-check key
1078    
1079     if (headMap) {
1080     fromStart = true;
1081     toKey = key;
1082     } else {
1083     toEnd = true;
1084     fromKey = key;
1085     }
1086     }
1087    
1088     SubMap(boolean fromStart, K fromKey, boolean toEnd, K toKey) {
1089     this.fromStart = fromStart;
1090     this.fromKey= fromKey;
1091     this.toEnd = toEnd;
1092     this.toKey = toKey;
1093     }
1094    
1095     public boolean isEmpty() {
1096 dl 1.7 return entrySet().isEmpty();
1097 dl 1.1 }
1098    
1099     public boolean containsKey(Object key) {
1100 dl 1.17 return inRange(key) && TreeMap.this.containsKey(key);
1101 dl 1.1 }
1102    
1103     public V get(Object key) {
1104 dl 1.17 if (!inRange(key))
1105 dl 1.1 return null;
1106     return TreeMap.this.get(key);
1107     }
1108    
1109     public V put(K key, V value) {
1110     if (!inRange(key))
1111     throw new IllegalArgumentException("key out of range");
1112     return TreeMap.this.put(key, value);
1113     }
1114    
1115     public V remove(Object key) {
1116 dl 1.17 if (!inRange(key))
1117 dl 1.1 return null;
1118     return TreeMap.this.remove(key);
1119     }
1120    
1121     public Comparator<? super K> comparator() {
1122     return comparator;
1123     }
1124    
1125     public K firstKey() {
1126     TreeMap.Entry<K,V> e = fromStart ? getFirstEntry() : getCeilingEntry(fromKey);
1127     K first = key(e);
1128     if (!toEnd && compare(first, toKey) >= 0)
1129 jsr166 1.11 throw new NoSuchElementException();
1130 dl 1.1 return first;
1131     }
1132    
1133     public K lastKey() {
1134     TreeMap.Entry<K,V> e = toEnd ? getLastEntry() : getLowerEntry(toKey);
1135     K last = key(e);
1136     if (!fromStart && compare(last, fromKey) < 0)
1137 jsr166 1.11 throw new NoSuchElementException();
1138 dl 1.1 return last;
1139     }
1140    
1141     public Map.Entry<K,V> firstEntry() {
1142 dl 1.8 TreeMap.Entry<K,V> e = fromStart ?
1143 dl 1.1 getFirstEntry() : getCeilingEntry(fromKey);
1144     if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1145     return null;
1146     return e;
1147     }
1148    
1149     public Map.Entry<K,V> lastEntry() {
1150 dl 1.8 TreeMap.Entry<K,V> e = toEnd ?
1151 dl 1.1 getLastEntry() : getLowerEntry(toKey);
1152     if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1153     return null;
1154     return e;
1155     }
1156    
1157     public Map.Entry<K,V> pollFirstEntry() {
1158 dl 1.8 TreeMap.Entry<K,V> e = fromStart ?
1159 dl 1.1 getFirstEntry() : getCeilingEntry(fromKey);
1160 dl 1.7 if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1161 dl 1.1 return null;
1162 dl 1.16 Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1163 dl 1.1 deleteEntry(e);
1164     return result;
1165     }
1166    
1167     public Map.Entry<K,V> pollLastEntry() {
1168 dl 1.8 TreeMap.Entry<K,V> e = toEnd ?
1169 dl 1.1 getLastEntry() : getLowerEntry(toKey);
1170 dl 1.7 if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1171 dl 1.1 return null;
1172 dl 1.16 Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1173 dl 1.1 deleteEntry(e);
1174     return result;
1175     }
1176    
1177     private TreeMap.Entry<K,V> subceiling(K key) {
1178     TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1179     getCeilingEntry(fromKey) : getCeilingEntry(key);
1180     if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1181     return null;
1182     return e;
1183     }
1184    
1185     public Map.Entry<K,V> ceilingEntry(K key) {
1186     TreeMap.Entry<K,V> e = subceiling(key);
1187 dl 1.16 return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1188 dl 1.1 }
1189    
1190     public K ceilingKey(K key) {
1191     TreeMap.Entry<K,V> e = subceiling(key);
1192     return e == null? null : e.key;
1193     }
1194    
1195    
1196     private TreeMap.Entry<K,V> subhigher(K key) {
1197     TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1198     getCeilingEntry(fromKey) : getHigherEntry(key);
1199     if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1200     return null;
1201     return e;
1202     }
1203    
1204     public Map.Entry<K,V> higherEntry(K key) {
1205     TreeMap.Entry<K,V> e = subhigher(key);
1206 dl 1.16 return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1207 dl 1.1 }
1208    
1209     public K higherKey(K key) {
1210     TreeMap.Entry<K,V> e = subhigher(key);
1211     return e == null? null : e.key;
1212     }
1213    
1214     private TreeMap.Entry<K,V> subfloor(K key) {
1215     TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1216     getLowerEntry(toKey) : getFloorEntry(key);
1217     if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1218     return null;
1219     return e;
1220     }
1221    
1222     public Map.Entry<K,V> floorEntry(K key) {
1223     TreeMap.Entry<K,V> e = subfloor(key);
1224 dl 1.16 return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1225 dl 1.1 }
1226    
1227     public K floorKey(K key) {
1228     TreeMap.Entry<K,V> e = subfloor(key);
1229     return e == null? null : e.key;
1230     }
1231    
1232     private TreeMap.Entry<K,V> sublower(K key) {
1233     TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1234     getLowerEntry(toKey) : getLowerEntry(key);
1235     if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1236     return null;
1237     return e;
1238     }
1239    
1240     public Map.Entry<K,V> lowerEntry(K key) {
1241     TreeMap.Entry<K,V> e = sublower(key);
1242 dl 1.16 return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1243 dl 1.1 }
1244    
1245     public K lowerKey(K key) {
1246     TreeMap.Entry<K,V> e = sublower(key);
1247     return e == null? null : e.key;
1248     }
1249    
1250 dl 1.7 private transient Set<Map.Entry<K,V>> entrySet = null;
1251 dl 1.1
1252     public Set<Map.Entry<K,V>> entrySet() {
1253 dl 1.7 Set<Map.Entry<K,V>> es = entrySet;
1254     return (es != null)? es : (entrySet = new EntrySetView());
1255 dl 1.1 }
1256    
1257     private class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1258     private transient int size = -1, sizeModCount;
1259    
1260     public int size() {
1261     if (size == -1 || sizeModCount != TreeMap.this.modCount) {
1262     size = 0; sizeModCount = TreeMap.this.modCount;
1263     Iterator i = iterator();
1264     while (i.hasNext()) {
1265     size++;
1266     i.next();
1267     }
1268     }
1269     return size;
1270     }
1271    
1272     public boolean isEmpty() {
1273     return !iterator().hasNext();
1274     }
1275    
1276     public boolean contains(Object o) {
1277     if (!(o instanceof Map.Entry))
1278     return false;
1279     Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1280     K key = entry.getKey();
1281     if (!inRange(key))
1282     return false;
1283     TreeMap.Entry node = getEntry(key);
1284     return node != null &&
1285     valEquals(node.getValue(), entry.getValue());
1286     }
1287    
1288     public boolean remove(Object o) {
1289     if (!(o instanceof Map.Entry))
1290     return false;
1291     Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1292     K key = entry.getKey();
1293     if (!inRange(key))
1294     return false;
1295     TreeMap.Entry<K,V> node = getEntry(key);
1296     if (node!=null && valEquals(node.getValue(),entry.getValue())){
1297     deleteEntry(node);
1298     return true;
1299     }
1300     return false;
1301     }
1302    
1303     public Iterator<Map.Entry<K,V>> iterator() {
1304     return new SubMapEntryIterator(
1305     (fromStart ? getFirstEntry() : getCeilingEntry(fromKey)),
1306     (toEnd ? null : getCeilingEntry(toKey)));
1307     }
1308     }
1309    
1310     private transient Set<Map.Entry<K,V>> descendingEntrySetView = null;
1311 dl 1.8 private transient Set<K> descendingKeySetView = null;
1312 dl 1.1
1313     public Set<Map.Entry<K,V>> descendingEntrySet() {
1314     Set<Map.Entry<K,V>> es = descendingEntrySetView;
1315 jsr166 1.14 return (es != null) ? es :
1316     (descendingEntrySetView = new DescendingEntrySetView());
1317 dl 1.1 }
1318    
1319     public Set<K> descendingKeySet() {
1320     Set<K> ks = descendingKeySetView;
1321 jsr166 1.14 return (ks != null) ? ks :
1322     (descendingKeySetView = new DescendingKeySetView());
1323 dl 1.1 }
1324    
1325     private class DescendingEntrySetView extends EntrySetView {
1326     public Iterator<Map.Entry<K,V>> iterator() {
1327     return new DescendingSubMapEntryIterator
1328     ((toEnd ? getLastEntry() : getLowerEntry(toKey)),
1329     (fromStart ? null : getLowerEntry(fromKey)));
1330     }
1331     }
1332    
1333     private class DescendingKeySetView extends AbstractSet<K> {
1334     public Iterator<K> iterator() {
1335     return new Iterator<K>() {
1336     private Iterator<Entry<K,V>> i = descendingEntrySet().iterator();
1337 dl 1.8
1338 dl 1.1 public boolean hasNext() { return i.hasNext(); }
1339     public K next() { return i.next().getKey(); }
1340     public void remove() { i.remove(); }
1341     };
1342     }
1343 dl 1.8
1344 dl 1.1 public int size() {
1345     return SubMap.this.size();
1346     }
1347 dl 1.8
1348 dl 1.1 public boolean contains(Object k) {
1349     return SubMap.this.containsKey(k);
1350     }
1351     }
1352    
1353 dl 1.4 public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1354 dl 1.1 if (!inRange2(fromKey))
1355     throw new IllegalArgumentException("fromKey out of range");
1356     if (!inRange2(toKey))
1357     throw new IllegalArgumentException("toKey out of range");
1358     return new SubMap(fromKey, toKey);
1359     }
1360    
1361 dl 1.4 public NavigableMap<K,V> navigableHeadMap(K toKey) {
1362 dl 1.1 if (!inRange2(toKey))
1363     throw new IllegalArgumentException("toKey out of range");
1364     return new SubMap(fromStart, fromKey, false, toKey);
1365     }
1366    
1367 dl 1.4 public NavigableMap<K,V> navigableTailMap(K fromKey) {
1368 dl 1.1 if (!inRange2(fromKey))
1369     throw new IllegalArgumentException("fromKey out of range");
1370     return new SubMap(false, fromKey, toEnd, toKey);
1371     }
1372    
1373 dl 1.4 public SortedMap<K,V> subMap(K fromKey, K toKey) {
1374     return navigableSubMap(fromKey, toKey);
1375     }
1376    
1377     public SortedMap<K,V> headMap(K toKey) {
1378     return navigableHeadMap(toKey);
1379     }
1380    
1381     public SortedMap<K,V> tailMap(K fromKey) {
1382     return navigableTailMap(fromKey);
1383     }
1384    
1385 dl 1.17 private boolean inRange(Object key) {
1386 dl 1.1 return (fromStart || compare(key, fromKey) >= 0) &&
1387     (toEnd || compare(key, toKey) < 0);
1388     }
1389    
1390     // This form allows the high endpoint (as well as all legit keys)
1391 dl 1.17 private boolean inRange2(Object key) {
1392 dl 1.1 return (fromStart || compare(key, fromKey) >= 0) &&
1393     (toEnd || compare(key, toKey) <= 0);
1394     }
1395     }
1396    
1397     /**
1398     * TreeMap Iterator.
1399     */
1400     abstract class PrivateEntryIterator<T> implements Iterator<T> {
1401     int expectedModCount = TreeMap.this.modCount;
1402     Entry<K,V> lastReturned = null;
1403     Entry<K,V> next;
1404    
1405     PrivateEntryIterator(Entry<K,V> first) {
1406     next = first;
1407     }
1408    
1409     public boolean hasNext() {
1410     return next != null;
1411     }
1412    
1413 jsr166 1.14 Entry<K,V> nextEntry() {
1414 dl 1.1 if (next == null)
1415     throw new NoSuchElementException();
1416     if (modCount != expectedModCount)
1417     throw new ConcurrentModificationException();
1418     lastReturned = next;
1419     next = successor(next);
1420     return lastReturned;
1421     }
1422    
1423     public void remove() {
1424     if (lastReturned == null)
1425     throw new IllegalStateException();
1426     if (modCount != expectedModCount)
1427     throw new ConcurrentModificationException();
1428     if (lastReturned.left != null && lastReturned.right != null)
1429     next = lastReturned;
1430     deleteEntry(lastReturned);
1431     expectedModCount++;
1432     lastReturned = null;
1433     }
1434     }
1435    
1436     class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1437     EntryIterator(Entry<K,V> first) {
1438     super(first);
1439     }
1440     public Map.Entry<K,V> next() {
1441     return nextEntry();
1442     }
1443     }
1444    
1445     class KeyIterator extends PrivateEntryIterator<K> {
1446     KeyIterator(Entry<K,V> first) {
1447     super(first);
1448     }
1449     public K next() {
1450     return nextEntry().key;
1451     }
1452     }
1453    
1454     class ValueIterator extends PrivateEntryIterator<V> {
1455     ValueIterator(Entry<K,V> first) {
1456     super(first);
1457     }
1458     public V next() {
1459     return nextEntry().value;
1460     }
1461     }
1462    
1463     class SubMapEntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1464     private final K firstExcludedKey;
1465    
1466     SubMapEntryIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1467     super(first);
1468     firstExcludedKey = (firstExcluded == null
1469     ? null
1470     : firstExcluded.key);
1471     }
1472    
1473     public boolean hasNext() {
1474     return next != null && next.key != firstExcludedKey;
1475     }
1476    
1477     public Map.Entry<K,V> next() {
1478     if (next == null || next.key == firstExcludedKey)
1479     throw new NoSuchElementException();
1480     return nextEntry();
1481     }
1482     }
1483    
1484     /**
1485     * Base for Descending Iterators.
1486     */
1487     abstract class DescendingPrivateEntryIterator<T> extends PrivateEntryIterator<T> {
1488     DescendingPrivateEntryIterator(Entry<K,V> first) {
1489     super(first);
1490     }
1491    
1492     Entry<K,V> nextEntry() {
1493     if (next == null)
1494     throw new NoSuchElementException();
1495     if (modCount != expectedModCount)
1496     throw new ConcurrentModificationException();
1497     lastReturned = next;
1498     next = predecessor(next);
1499     return lastReturned;
1500     }
1501     }
1502    
1503     class DescendingEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1504     DescendingEntryIterator(Entry<K,V> first) {
1505     super(first);
1506     }
1507     public Map.Entry<K,V> next() {
1508     return nextEntry();
1509     }
1510     }
1511    
1512     class DescendingKeyIterator extends DescendingPrivateEntryIterator<K> {
1513     DescendingKeyIterator(Entry<K,V> first) {
1514     super(first);
1515     }
1516     public K next() {
1517     return nextEntry().key;
1518     }
1519     }
1520    
1521    
1522     class DescendingSubMapEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1523     private final K lastExcludedKey;
1524    
1525     DescendingSubMapEntryIterator(Entry<K,V> last, Entry<K,V> lastExcluded) {
1526     super(last);
1527     lastExcludedKey = (lastExcluded == null
1528     ? null
1529     : lastExcluded.key);
1530     }
1531    
1532     public boolean hasNext() {
1533     return next != null && next.key != lastExcludedKey;
1534     }
1535    
1536     public Map.Entry<K,V> next() {
1537     if (next == null || next.key == lastExcludedKey)
1538     throw new NoSuchElementException();
1539     return nextEntry();
1540     }
1541    
1542     }
1543    
1544     /**
1545     * Compares two keys using the correct comparison method for this TreeMap.
1546     */
1547 dl 1.16 private int compare(Object k1, Object k2) {
1548     return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1549     : comparator.compare((K)k1, (K)k2);
1550 dl 1.1 }
1551    
1552     /**
1553 jsr166 1.18 * Test two values for equality. Differs from o1.equals(o2) only in
1554 dl 1.1 * that it copes with <tt>null</tt> o1 properly.
1555     */
1556     private static boolean valEquals(Object o1, Object o2) {
1557     return (o1==null ? o2==null : o1.equals(o2));
1558     }
1559    
1560     private static final boolean RED = false;
1561     private static final boolean BLACK = true;
1562    
1563     /**
1564     * Node in the Tree. Doubles as a means to pass key-value pairs back to
1565     * user (see Map.Entry).
1566     */
1567    
1568     static class Entry<K,V> implements Map.Entry<K,V> {
1569     K key;
1570     V value;
1571     Entry<K,V> left = null;
1572     Entry<K,V> right = null;
1573     Entry<K,V> parent;
1574     boolean color = BLACK;
1575    
1576     /**
1577     * Make a new cell with given key, value, and parent, and with
1578     * <tt>null</tt> child links, and BLACK color.
1579     */
1580     Entry(K key, V value, Entry<K,V> parent) {
1581     this.key = key;
1582     this.value = value;
1583     this.parent = parent;
1584     }
1585    
1586     /**
1587     * Returns the key.
1588     *
1589 jsr166 1.14 * @return the key
1590 dl 1.1 */
1591     public K getKey() {
1592     return key;
1593     }
1594    
1595     /**
1596     * Returns the value associated with the key.
1597     *
1598 jsr166 1.14 * @return the value associated with the key
1599 dl 1.1 */
1600     public V getValue() {
1601     return value;
1602     }
1603    
1604     /**
1605     * Replaces the value currently associated with the key with the given
1606     * value.
1607     *
1608     * @return the value associated with the key before this method was
1609 jsr166 1.14 * called
1610 dl 1.1 */
1611     public V setValue(V value) {
1612     V oldValue = this.value;
1613     this.value = value;
1614     return oldValue;
1615     }
1616    
1617     public boolean equals(Object o) {
1618     if (!(o instanceof Map.Entry))
1619     return false;
1620     Map.Entry e = (Map.Entry)o;
1621    
1622     return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
1623     }
1624    
1625     public int hashCode() {
1626     int keyHash = (key==null ? 0 : key.hashCode());
1627     int valueHash = (value==null ? 0 : value.hashCode());
1628     return keyHash ^ valueHash;
1629     }
1630    
1631     public String toString() {
1632     return key + "=" + value;
1633     }
1634     }
1635    
1636     /**
1637     * Returns the first Entry in the TreeMap (according to the TreeMap's
1638     * key-sort function). Returns null if the TreeMap is empty.
1639     */
1640     private Entry<K,V> getFirstEntry() {
1641     Entry<K,V> p = root;
1642     if (p != null)
1643     while (p.left != null)
1644     p = p.left;
1645     return p;
1646     }
1647    
1648     /**
1649     * Returns the last Entry in the TreeMap (according to the TreeMap's
1650     * key-sort function). Returns null if the TreeMap is empty.
1651     */
1652     private Entry<K,V> getLastEntry() {
1653     Entry<K,V> p = root;
1654     if (p != null)
1655     while (p.right != null)
1656     p = p.right;
1657     return p;
1658     }
1659    
1660     /**
1661     * Returns the successor of the specified Entry, or null if no such.
1662     */
1663     private Entry<K,V> successor(Entry<K,V> t) {
1664     if (t == null)
1665     return null;
1666     else if (t.right != null) {
1667     Entry<K,V> p = t.right;
1668     while (p.left != null)
1669     p = p.left;
1670     return p;
1671     } else {
1672     Entry<K,V> p = t.parent;
1673     Entry<K,V> ch = t;
1674     while (p != null && ch == p.right) {
1675     ch = p;
1676     p = p.parent;
1677     }
1678     return p;
1679     }
1680     }
1681    
1682     /**
1683     * Returns the predecessor of the specified Entry, or null if no such.
1684     */
1685     private Entry<K,V> predecessor(Entry<K,V> t) {
1686     if (t == null)
1687     return null;
1688     else if (t.left != null) {
1689     Entry<K,V> p = t.left;
1690     while (p.right != null)
1691     p = p.right;
1692     return p;
1693     } else {
1694     Entry<K,V> p = t.parent;
1695     Entry<K,V> ch = t;
1696     while (p != null && ch == p.left) {
1697     ch = p;
1698     p = p.parent;
1699     }
1700     return p;
1701     }
1702     }
1703    
1704     /**
1705     * Balancing operations.
1706     *
1707     * Implementations of rebalancings during insertion and deletion are
1708     * slightly different than the CLR version. Rather than using dummy
1709     * nilnodes, we use a set of accessors that deal properly with null. They
1710     * are used to avoid messiness surrounding nullness checks in the main
1711     * algorithms.
1712     */
1713    
1714     private static <K,V> boolean colorOf(Entry<K,V> p) {
1715     return (p == null ? BLACK : p.color);
1716     }
1717    
1718     private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) {
1719     return (p == null ? null: p.parent);
1720     }
1721    
1722     private static <K,V> void setColor(Entry<K,V> p, boolean c) {
1723     if (p != null)
1724     p.color = c;
1725     }
1726    
1727     private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) {
1728     return (p == null) ? null: p.left;
1729     }
1730    
1731     private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) {
1732     return (p == null) ? null: p.right;
1733     }
1734    
1735     /** From CLR **/
1736     private void rotateLeft(Entry<K,V> p) {
1737     Entry<K,V> r = p.right;
1738     p.right = r.left;
1739     if (r.left != null)
1740     r.left.parent = p;
1741     r.parent = p.parent;
1742     if (p.parent == null)
1743     root = r;
1744     else if (p.parent.left == p)
1745     p.parent.left = r;
1746     else
1747     p.parent.right = r;
1748     r.left = p;
1749     p.parent = r;
1750     }
1751    
1752     /** From CLR **/
1753     private void rotateRight(Entry<K,V> p) {
1754     Entry<K,V> l = p.left;
1755     p.left = l.right;
1756     if (l.right != null) l.right.parent = p;
1757     l.parent = p.parent;
1758     if (p.parent == null)
1759     root = l;
1760     else if (p.parent.right == p)
1761     p.parent.right = l;
1762     else p.parent.left = l;
1763     l.right = p;
1764     p.parent = l;
1765     }
1766    
1767    
1768     /** From CLR **/
1769     private void fixAfterInsertion(Entry<K,V> x) {
1770     x.color = RED;
1771    
1772     while (x != null && x != root && x.parent.color == RED) {
1773     if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
1774     Entry<K,V> y = rightOf(parentOf(parentOf(x)));
1775     if (colorOf(y) == RED) {
1776     setColor(parentOf(x), BLACK);
1777     setColor(y, BLACK);
1778     setColor(parentOf(parentOf(x)), RED);
1779     x = parentOf(parentOf(x));
1780     } else {
1781     if (x == rightOf(parentOf(x))) {
1782     x = parentOf(x);
1783     rotateLeft(x);
1784     }
1785     setColor(parentOf(x), BLACK);
1786     setColor(parentOf(parentOf(x)), RED);
1787     if (parentOf(parentOf(x)) != null)
1788     rotateRight(parentOf(parentOf(x)));
1789     }
1790     } else {
1791     Entry<K,V> y = leftOf(parentOf(parentOf(x)));
1792     if (colorOf(y) == RED) {
1793     setColor(parentOf(x), BLACK);
1794     setColor(y, BLACK);
1795     setColor(parentOf(parentOf(x)), RED);
1796     x = parentOf(parentOf(x));
1797     } else {
1798     if (x == leftOf(parentOf(x))) {
1799     x = parentOf(x);
1800     rotateRight(x);
1801     }
1802     setColor(parentOf(x), BLACK);
1803     setColor(parentOf(parentOf(x)), RED);
1804     if (parentOf(parentOf(x)) != null)
1805     rotateLeft(parentOf(parentOf(x)));
1806     }
1807     }
1808     }
1809     root.color = BLACK;
1810     }
1811    
1812     /**
1813     * Delete node p, and then rebalance the tree.
1814     */
1815    
1816     private void deleteEntry(Entry<K,V> p) {
1817     decrementSize();
1818    
1819     // If strictly internal, copy successor's element to p and then make p
1820     // point to successor.
1821     if (p.left != null && p.right != null) {
1822     Entry<K,V> s = successor (p);
1823     p.key = s.key;
1824     p.value = s.value;
1825     p = s;
1826     } // p has 2 children
1827    
1828     // Start fixup at replacement node, if it exists.
1829     Entry<K,V> replacement = (p.left != null ? p.left : p.right);
1830    
1831     if (replacement != null) {
1832     // Link replacement to parent
1833     replacement.parent = p.parent;
1834     if (p.parent == null)
1835     root = replacement;
1836     else if (p == p.parent.left)
1837     p.parent.left = replacement;
1838     else
1839     p.parent.right = replacement;
1840    
1841     // Null out links so they are OK to use by fixAfterDeletion.
1842     p.left = p.right = p.parent = null;
1843    
1844     // Fix replacement
1845     if (p.color == BLACK)
1846     fixAfterDeletion(replacement);
1847     } else if (p.parent == null) { // return if we are the only node.
1848     root = null;
1849     } else { // No children. Use self as phantom replacement and unlink.
1850     if (p.color == BLACK)
1851     fixAfterDeletion(p);
1852    
1853     if (p.parent != null) {
1854     if (p == p.parent.left)
1855     p.parent.left = null;
1856     else if (p == p.parent.right)
1857     p.parent.right = null;
1858     p.parent = null;
1859     }
1860     }
1861     }
1862    
1863     /** From CLR **/
1864     private void fixAfterDeletion(Entry<K,V> x) {
1865     while (x != root && colorOf(x) == BLACK) {
1866     if (x == leftOf(parentOf(x))) {
1867     Entry<K,V> sib = rightOf(parentOf(x));
1868    
1869     if (colorOf(sib) == RED) {
1870     setColor(sib, BLACK);
1871     setColor(parentOf(x), RED);
1872     rotateLeft(parentOf(x));
1873     sib = rightOf(parentOf(x));
1874     }
1875    
1876     if (colorOf(leftOf(sib)) == BLACK &&
1877     colorOf(rightOf(sib)) == BLACK) {
1878     setColor(sib, RED);
1879     x = parentOf(x);
1880     } else {
1881     if (colorOf(rightOf(sib)) == BLACK) {
1882     setColor(leftOf(sib), BLACK);
1883     setColor(sib, RED);
1884     rotateRight(sib);
1885     sib = rightOf(parentOf(x));
1886     }
1887     setColor(sib, colorOf(parentOf(x)));
1888     setColor(parentOf(x), BLACK);
1889     setColor(rightOf(sib), BLACK);
1890     rotateLeft(parentOf(x));
1891     x = root;
1892     }
1893     } else { // symmetric
1894     Entry<K,V> sib = leftOf(parentOf(x));
1895    
1896     if (colorOf(sib) == RED) {
1897     setColor(sib, BLACK);
1898     setColor(parentOf(x), RED);
1899     rotateRight(parentOf(x));
1900     sib = leftOf(parentOf(x));
1901     }
1902    
1903     if (colorOf(rightOf(sib)) == BLACK &&
1904     colorOf(leftOf(sib)) == BLACK) {
1905     setColor(sib, RED);
1906     x = parentOf(x);
1907     } else {
1908     if (colorOf(leftOf(sib)) == BLACK) {
1909     setColor(rightOf(sib), BLACK);
1910     setColor(sib, RED);
1911     rotateLeft(sib);
1912     sib = leftOf(parentOf(x));
1913     }
1914     setColor(sib, colorOf(parentOf(x)));
1915     setColor(parentOf(x), BLACK);
1916     setColor(leftOf(sib), BLACK);
1917     rotateRight(parentOf(x));
1918     x = root;
1919     }
1920     }
1921     }
1922    
1923     setColor(x, BLACK);
1924     }
1925    
1926     private static final long serialVersionUID = 919286545866124006L;
1927    
1928     /**
1929     * Save the state of the <tt>TreeMap</tt> instance to a stream (i.e.,
1930     * serialize it).
1931     *
1932     * @serialData The <i>size</i> of the TreeMap (the number of key-value
1933     * mappings) is emitted (int), followed by the key (Object)
1934     * and value (Object) for each key-value mapping represented
1935     * by the TreeMap. The key-value mappings are emitted in
1936     * key-order (as determined by the TreeMap's Comparator,
1937     * or by the keys' natural ordering if the TreeMap has no
1938     * Comparator).
1939     */
1940     private void writeObject(java.io.ObjectOutputStream s)
1941     throws java.io.IOException {
1942     // Write out the Comparator and any hidden stuff
1943     s.defaultWriteObject();
1944    
1945     // Write out size (number of Mappings)
1946     s.writeInt(size);
1947    
1948     // Write out keys and values (alternating)
1949 jsr166 1.14 for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
1950 dl 1.1 Map.Entry<K,V> e = i.next();
1951     s.writeObject(e.getKey());
1952     s.writeObject(e.getValue());
1953     }
1954     }
1955    
1956    
1957    
1958     /**
1959     * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e.,
1960     * deserialize it).
1961     */
1962     private void readObject(final java.io.ObjectInputStream s)
1963     throws java.io.IOException, ClassNotFoundException {
1964     // Read in the Comparator and any hidden stuff
1965     s.defaultReadObject();
1966    
1967     // Read in size
1968     int size = s.readInt();
1969    
1970     buildFromSorted(size, null, s, null);
1971     }
1972    
1973     /** Intended to be called only from TreeSet.readObject **/
1974     void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
1975     throws java.io.IOException, ClassNotFoundException {
1976     buildFromSorted(size, null, s, defaultVal);
1977     }
1978    
1979     /** Intended to be called only from TreeSet.addAll **/
1980 jsr166 1.12 void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
1981 dl 1.1 try {
1982     buildFromSorted(set.size(), set.iterator(), null, defaultVal);
1983     } catch (java.io.IOException cannotHappen) {
1984     } catch (ClassNotFoundException cannotHappen) {
1985     }
1986     }
1987    
1988    
1989     /**
1990     * Linear time tree building algorithm from sorted data. Can accept keys
1991     * and/or values from iterator or stream. This leads to too many
1992     * parameters, but seems better than alternatives. The four formats
1993     * that this method accepts are:
1994     *
1995     * 1) An iterator of Map.Entries. (it != null, defaultVal == null).
1996     * 2) An iterator of keys. (it != null, defaultVal != null).
1997     * 3) A stream of alternating serialized keys and values.
1998     * (it == null, defaultVal == null).
1999     * 4) A stream of serialized keys. (it == null, defaultVal != null).
2000     *
2001     * It is assumed that the comparator of the TreeMap is already set prior
2002     * to calling this method.
2003     *
2004     * @param size the number of keys (or key-value pairs) to be read from
2005 jsr166 1.14 * the iterator or stream
2006 dl 1.1 * @param it If non-null, new entries are created from entries
2007     * or keys read from this iterator.
2008     * @param str If non-null, new entries are created from keys and
2009     * possibly values read from this stream in serialized form.
2010     * Exactly one of it and str should be non-null.
2011     * @param defaultVal if non-null, this default value is used for
2012     * each value in the map. If null, each value is read from
2013     * iterator or stream, as described above.
2014     * @throws IOException propagated from stream reads. This cannot
2015     * occur if str is null.
2016     * @throws ClassNotFoundException propagated from readObject.
2017     * This cannot occur if str is null.
2018     */
2019     private
2020     void buildFromSorted(int size, Iterator it,
2021     java.io.ObjectInputStream str,
2022     V defaultVal)
2023     throws java.io.IOException, ClassNotFoundException {
2024     this.size = size;
2025     root =
2026     buildFromSorted(0, 0, size-1, computeRedLevel(size),
2027     it, str, defaultVal);
2028     }
2029    
2030     /**
2031     * Recursive "helper method" that does the real work of the
2032     * of the previous method. Identically named parameters have
2033     * identical definitions. Additional parameters are documented below.
2034     * It is assumed that the comparator and size fields of the TreeMap are
2035     * already set prior to calling this method. (It ignores both fields.)
2036     *
2037     * @param level the current level of tree. Initial call should be 0.
2038     * @param lo the first element index of this subtree. Initial should be 0.
2039     * @param hi the last element index of this subtree. Initial should be
2040 jsr166 1.14 * size-1.
2041 dl 1.1 * @param redLevel the level at which nodes should be red.
2042     * Must be equal to computeRedLevel for tree of this size.
2043     */
2044     private final Entry<K,V> buildFromSorted(int level, int lo, int hi,
2045     int redLevel,
2046     Iterator it,
2047     java.io.ObjectInputStream str,
2048     V defaultVal)
2049     throws java.io.IOException, ClassNotFoundException {
2050     /*
2051     * Strategy: The root is the middlemost element. To get to it, we
2052     * have to first recursively construct the entire left subtree,
2053     * so as to grab all of its elements. We can then proceed with right
2054     * subtree.
2055     *
2056     * The lo and hi arguments are the minimum and maximum
2057     * indices to pull out of the iterator or stream for current subtree.
2058     * They are not actually indexed, we just proceed sequentially,
2059     * ensuring that items are extracted in corresponding order.
2060     */
2061    
2062     if (hi < lo) return null;
2063    
2064     int mid = (lo + hi) / 2;
2065    
2066     Entry<K,V> left = null;
2067     if (lo < mid)
2068     left = buildFromSorted(level+1, lo, mid - 1, redLevel,
2069     it, str, defaultVal);
2070    
2071     // extract key and/or value from iterator or stream
2072     K key;
2073     V value;
2074     if (it != null) {
2075     if (defaultVal==null) {
2076     Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
2077     key = entry.getKey();
2078     value = entry.getValue();
2079     } else {
2080     key = (K)it.next();
2081     value = defaultVal;
2082     }
2083     } else { // use stream
2084     key = (K) str.readObject();
2085     value = (defaultVal != null ? defaultVal : (V) str.readObject());
2086     }
2087    
2088     Entry<K,V> middle = new Entry<K,V>(key, value, null);
2089    
2090     // color nodes in non-full bottommost level red
2091     if (level == redLevel)
2092     middle.color = RED;
2093    
2094     if (left != null) {
2095     middle.left = left;
2096     left.parent = middle;
2097     }
2098    
2099     if (mid < hi) {
2100     Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
2101     it, str, defaultVal);
2102     middle.right = right;
2103     right.parent = middle;
2104     }
2105    
2106     return middle;
2107     }
2108    
2109     /**
2110     * Find the level down to which to assign all nodes BLACK. This is the
2111     * last `full' level of the complete binary tree produced by
2112     * buildTree. The remaining nodes are colored RED. (This makes a `nice'
2113     * set of color assignments wrt future insertions.) This level number is
2114     * computed by finding the number of splits needed to reach the zeroeth
2115     * node. (The answer is ~lg(N), but in any case must be computed by same
2116     * quick O(lg(N)) loop.)
2117     */
2118     private static int computeRedLevel(int sz) {
2119     int level = 0;
2120     for (int m = sz - 1; m >= 0; m = m / 2 - 1)
2121     level++;
2122     return level;
2123     }
2124     }