ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.28
Committed: Wed Apr 19 15:07:14 2006 UTC (18 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.27: +675 -384 lines
Log Message:
Updated Navigable interfaces ind implementations

File Contents

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