ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.6
Committed: Wed Mar 23 11:20:27 2005 UTC (19 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.5: +5 -7 lines
Log Message:
Documentation improvements

File Contents

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