ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.24
Committed: Sat Sep 10 20:01:23 2005 UTC (18 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.23: +15 -10 lines
Log Message:
get

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