ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.29
Committed: Thu Apr 20 20:34:37 2006 UTC (18 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.28: +460 -419 lines
Log Message:
Simplify Navigable method names

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