ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.21
Committed: Fri Jun 24 00:26:57 2005 UTC (18 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.20: +2 -2 lines
Log Message:
doc fixes

File Contents

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