ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.13
Committed: Wed May 11 11:16:08 2005 UTC (19 years ago) by dl
Branch: MAIN
Changes since 1.12: +5 -0 lines
Log Message:
Trap null in empty maps

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
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<? super K> k = (Comparable<? super 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 if (key == null) {
560 if (comparator == null)
561 throw new NullPointerException();
562 comparator.compare(key, key);
563 }
564 incrementSize();
565 root = new Entry<K,V>(key, value, null);
566 return null;
567 }
568
569 while (true) {
570 int cmp = compare(key, t.key);
571 if (cmp == 0) {
572 return t.setValue(value);
573 } else if (cmp < 0) {
574 if (t.left != null) {
575 t = t.left;
576 } else {
577 incrementSize();
578 t.left = new Entry<K,V>(key, value, t);
579 fixAfterInsertion(t.left);
580 return null;
581 }
582 } else { // cmp > 0
583 if (t.right != null) {
584 t = t.right;
585 } else {
586 incrementSize();
587 t.right = new Entry<K,V>(key, value, t);
588 fixAfterInsertion(t.right);
589 return null;
590 }
591 }
592 }
593 }
594
595 /**
596 * Removes the mapping for this key from this TreeMap if present.
597 *
598 * @param key key for which mapping should be removed
599 * @return the previous value associated with specified key, or <tt>null</tt>
600 * if there was no mapping for key. A <tt>null</tt> return can
601 * also indicate that the map previously associated
602 * <tt>null</tt> with the specified key.
603 *
604 * @throws ClassCastException if key cannot be compared with the keys
605 * currently in the map.
606 * @throws NullPointerException if key is <tt>null</tt> and this map uses
607 * natural order, or its comparator does not tolerate
608 * <tt>null</tt> keys.
609 */
610 public V remove(Object key) {
611 Entry<K,V> p = getEntry(key);
612 if (p == null)
613 return null;
614
615 V oldValue = p.value;
616 deleteEntry(p);
617 return oldValue;
618 }
619
620 /**
621 * Removes all mappings from this TreeMap.
622 */
623 public void clear() {
624 modCount++;
625 size = 0;
626 root = null;
627 }
628
629 /**
630 * Returns a shallow copy of this <tt>TreeMap</tt> instance. (The keys and
631 * values themselves are not cloned.)
632 *
633 * @return a shallow copy of this Map.
634 */
635 public Object clone() {
636 TreeMap<K,V> clone = null;
637 try {
638 clone = (TreeMap<K,V>) super.clone();
639 } catch (CloneNotSupportedException e) {
640 throw new InternalError();
641 }
642
643 // Put clone into "virgin" state (except for comparator)
644 clone.root = null;
645 clone.size = 0;
646 clone.modCount = 0;
647 clone.entrySet = null;
648 clone.descendingEntrySet = null;
649 clone.descendingKeySet = null;
650
651 // Initialize clone with our mappings
652 try {
653 clone.buildFromSorted(size, entrySet().iterator(), null, null);
654 } catch (java.io.IOException cannotHappen) {
655 } catch (ClassNotFoundException cannotHappen) {
656 }
657
658 return clone;
659 }
660
661 // NavigableMap API methods
662
663 /**
664 * Returns a key-value mapping associated with the least
665 * key in this map, or <tt>null</tt> if the map is empty.
666 *
667 * @return an Entry with least key, or <tt>null</tt>
668 * if the map is empty.
669 */
670 public Map.Entry<K,V> firstEntry() {
671 Entry<K,V> e = getFirstEntry();
672 return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e);
673 }
674
675 /**
676 * Returns a key-value mapping associated with the greatest
677 * key in this map, or <tt>null</tt> if the map is empty.
678 *
679 * @return an Entry with greatest key, or <tt>null</tt>
680 * if the map is empty.
681 */
682 public Map.Entry<K,V> lastEntry() {
683 Entry<K,V> e = getLastEntry();
684 return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e);
685 }
686
687 /**
688 * Removes and returns a key-value mapping associated with
689 * the least key in this map, or <tt>null</tt> if the map is empty.
690 *
691 * @return the removed first entry of this map, or <tt>null</tt>
692 * if the map is empty.
693 */
694 public Map.Entry<K,V> pollFirstEntry() {
695 Entry<K,V> p = getFirstEntry();
696 if (p == null)
697 return null;
698 Map.Entry result = new AbstractMap.SimpleImmutableEntry(p);
699 deleteEntry(p);
700 return result;
701 }
702
703 /**
704 * Removes and returns a key-value mapping associated with
705 * the greatest key in this map, or <tt>null</tt> if the map is empty.
706 *
707 * @return the removed last entry of this map, or <tt>null</tt>
708 * if the map is empty.
709 */
710 public Map.Entry<K,V> pollLastEntry() {
711 Entry<K,V> p = getLastEntry();
712 if (p == null)
713 return null;
714 Map.Entry result = new AbstractMap.SimpleImmutableEntry(p);
715 deleteEntry(p);
716 return result;
717 }
718
719 /**
720 * Returns a key-value mapping associated with the least key
721 * greater than or equal to the given key, or <tt>null</tt> if
722 * there is no such entry.
723 *
724 * @param key the key.
725 * @return an Entry associated with ceiling of given key, or
726 * <tt>null</tt> if there is no such Entry.
727 * @throws ClassCastException if key cannot be compared with the
728 * keys currently in the map.
729 * @throws NullPointerException if key is <tt>null</tt> and this map uses
730 * natural order, or its comparator does not tolerate
731 * <tt>null</tt> keys.
732 */
733 public Map.Entry<K,V> ceilingEntry(K key) {
734 Entry<K,V> e = getCeilingEntry(key);
735 return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e);
736 }
737
738
739 /**
740 * Returns least key greater than or equal to the given key, or
741 * <tt>null</tt> if there is no such key.
742 *
743 * @param key the key.
744 * @return the ceiling key, or <tt>null</tt>
745 * if there is no such key.
746 * @throws ClassCastException if key cannot be compared with the keys
747 * currently in the map.
748 * @throws NullPointerException if key is <tt>null</tt> and this map uses
749 * natural order, or its comparator does not tolerate
750 * <tt>null</tt> keys.
751 */
752 public K ceilingKey(K key) {
753 Entry<K,V> e = getCeilingEntry(key);
754 return (e == null)? null : e.key;
755 }
756
757
758
759 /**
760 * Returns a key-value mapping associated with the greatest key
761 * less than or equal to the given key, or <tt>null</tt> if there
762 * is no such entry.
763 *
764 * @param key the key.
765 * @return an Entry associated with floor of given key, or <tt>null</tt>
766 * if there is no such Entry.
767 * @throws ClassCastException if key cannot be compared with the keys
768 * currently in the map.
769 * @throws NullPointerException if key is <tt>null</tt> and this map uses
770 * natural order, or its comparator does not tolerate
771 * <tt>null</tt> keys.
772 */
773 public Map.Entry<K,V> floorEntry(K key) {
774 Entry<K,V> e = getFloorEntry(key);
775 return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e);
776 }
777
778 /**
779 * Returns the greatest key
780 * less than or equal to the given key, or <tt>null</tt> if there
781 * is no such key.
782 *
783 * @param key the key.
784 * @return the floor of given key, or <tt>null</tt> if there is no
785 * such key.
786 * @throws ClassCastException if key cannot be compared with the keys
787 * currently in the map.
788 * @throws NullPointerException if key is <tt>null</tt> and this map uses
789 * natural order, or its comparator does not tolerate
790 * <tt>null</tt> keys.
791 */
792 public K floorKey(K key) {
793 Entry<K,V> e = getFloorEntry(key);
794 return (e == null)? null : e.key;
795 }
796
797 /**
798 * Returns a key-value mapping associated with the least key
799 * strictly greater than the given key, or <tt>null</tt> if there
800 * is no such entry.
801 *
802 * @param key the key.
803 * @return an Entry with least key greater than the given key, or
804 * <tt>null</tt> if there is no such Entry.
805 * @throws ClassCastException if key cannot be compared with the keys
806 * currently in the map.
807 * @throws NullPointerException if key is <tt>null</tt> and this map uses
808 * natural order, or its comparator does not tolerate
809 * <tt>null</tt> keys.
810 */
811 public Map.Entry<K,V> higherEntry(K key) {
812 Entry<K,V> e = getHigherEntry(key);
813 return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e);
814 }
815
816 /**
817 * Returns the least key strictly greater than the given key, or
818 * <tt>null</tt> if there is no such key.
819 *
820 * @param key the key.
821 * @return the least key greater than the given key, or
822 * <tt>null</tt> if there is no such key.
823 * @throws ClassCastException if key cannot be compared with the keys
824 * currently in the map.
825 * @throws NullPointerException if key is <tt>null</tt> and this map uses
826 * natural order, or its comparator does not tolerate
827 * <tt>null</tt> keys.
828 */
829 public K higherKey(K key) {
830 Entry<K,V> e = getHigherEntry(key);
831 return (e == null)? null : e.key;
832 }
833
834 /**
835 * Returns a key-value mapping associated with the greatest
836 * key strictly less than the given key, or <tt>null</tt> if there is no
837 * such entry.
838 *
839 * @param key the key.
840 * @return an Entry with greatest key less than the given
841 * key, or <tt>null</tt> if there is no such Entry.
842 * @throws ClassCastException if key cannot be compared with the keys
843 * currently in the map.
844 * @throws NullPointerException if key is <tt>null</tt> and this map uses
845 * natural order, or its comparator does not tolerate
846 * <tt>null</tt> keys.
847 */
848 public Map.Entry<K,V> lowerEntry(K key) {
849 Entry<K,V> e = getLowerEntry(key);
850 return (e == null)? null : new AbstractMap.SimpleImmutableEntry(e);
851 }
852
853 /**
854 * Returns the greatest key strictly less than the given key, or
855 * <tt>null</tt> if there is no such key.
856 *
857 * @param key the key.
858 * @return the greatest key less than the given
859 * key, or <tt>null</tt> if there is no such key.
860 * @throws ClassCastException if key cannot be compared with the keys
861 * currently in the map.
862 * @throws NullPointerException if key is <tt>null</tt> and this map uses
863 * natural order, or its comparator does not tolerate
864 * <tt>null</tt> keys.
865 */
866 public K lowerKey(K key) {
867 Entry<K,V> e = getLowerEntry(key);
868 return (e == null)? null : e.key;
869 }
870
871 // Views
872
873 /**
874 * Fields initialized to contain an instance of the entry set view
875 * the first time this view is requested. Views are stateless, so
876 * there's no reason to create more than one.
877 */
878 private transient Set<Map.Entry<K,V>> entrySet = null;
879 private transient Set<Map.Entry<K,V>> descendingEntrySet = null;
880 private transient Set<K> descendingKeySet = null;
881
882 /**
883 * Returns a Set view of the keys contained in this map. The set's
884 * iterator will return the keys in ascending order. The set is backed by
885 * this <tt>TreeMap</tt> instance, so changes to this map are reflected in
886 * the Set, and vice-versa. The Set supports element removal, which
887 * removes the corresponding mapping from the map, via the
888 * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>,
889 * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not support
890 * the <tt>add</tt> or <tt>addAll</tt> operations.
891 *
892 * @return a set view of the keys contained in this TreeMap.
893 */
894 public Set<K> keySet() {
895 Set<K> ks = keySet;
896 return (ks != null) ? ks : (keySet = new KeySet());
897 }
898
899 class KeySet extends AbstractSet<K> {
900 public Iterator<K> iterator() {
901 return new KeyIterator(getFirstEntry());
902 }
903
904 public int size() {
905 return TreeMap.this.size();
906 }
907
908 public boolean contains(Object o) {
909 return containsKey(o);
910 }
911
912 public boolean remove(Object o) {
913 int oldSize = size;
914 TreeMap.this.remove(o);
915 return size != oldSize;
916 }
917
918 public void clear() {
919 TreeMap.this.clear();
920 }
921 }
922
923 /**
924 * Returns a collection view of the values contained in this map. The
925 * collection's iterator will return the values in the order that their
926 * corresponding keys appear in the tree. The collection is backed by
927 * this <tt>TreeMap</tt> instance, so changes to this map are reflected in
928 * the collection, and vice-versa. The collection supports element
929 * removal, which removes the corresponding mapping from the map through
930 * the <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
931 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
932 * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
933 *
934 * @return a collection view of the values contained in this map.
935 */
936 public Collection<V> values() {
937 Collection<V> vs = values;
938 return (vs != null) ? vs : (values = new Values());
939 }
940
941 class Values extends AbstractCollection<V> {
942 public Iterator<V> iterator() {
943 return new ValueIterator(getFirstEntry());
944 }
945
946 public int size() {
947 return TreeMap.this.size();
948 }
949
950 public boolean contains(Object o) {
951 for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
952 if (valEquals(e.getValue(), o))
953 return true;
954 return false;
955 }
956
957 public boolean remove(Object o) {
958 for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
959 if (valEquals(e.getValue(), o)) {
960 deleteEntry(e);
961 return true;
962 }
963 }
964 return false;
965 }
966
967 public void clear() {
968 TreeMap.this.clear();
969 }
970 }
971
972 /**
973 * Returns a set view of the mappings contained in this map. The set's
974 * iterator returns the mappings in ascending key order. Each element in
975 * the returned set is a <tt>Map.Entry</tt>. The set is backed by this
976 * map, so changes to this map are reflected in the set, and vice-versa.
977 * The set supports element removal, which removes the corresponding
978 * mapping from the TreeMap, through the <tt>Iterator.remove</tt>,
979 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
980 * <tt>clear</tt> operations. It does not support the <tt>add</tt> or
981 * <tt>addAll</tt> operations.
982 *
983 * @return a set view of the mappings contained in this map.
984 * @see Map.Entry
985 */
986 public Set<Map.Entry<K,V>> entrySet() {
987 Set<Map.Entry<K,V>> es = entrySet;
988 return (es != null) ? es : (entrySet = new EntrySet());
989 }
990
991 class EntrySet extends AbstractSet<Map.Entry<K,V>> {
992 public Iterator<Map.Entry<K,V>> iterator() {
993 return new EntryIterator(getFirstEntry());
994 }
995
996 public boolean contains(Object o) {
997 if (!(o instanceof Map.Entry))
998 return false;
999 Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1000 V value = entry.getValue();
1001 Entry<K,V> p = getEntry(entry.getKey());
1002 return p != null && valEquals(p.getValue(), value);
1003 }
1004
1005 public boolean remove(Object o) {
1006 if (!(o instanceof Map.Entry))
1007 return false;
1008 Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1009 V value = entry.getValue();
1010 Entry<K,V> p = getEntry(entry.getKey());
1011 if (p != null && valEquals(p.getValue(), value)) {
1012 deleteEntry(p);
1013 return true;
1014 }
1015 return false;
1016 }
1017
1018 public int size() {
1019 return TreeMap.this.size();
1020 }
1021
1022 public void clear() {
1023 TreeMap.this.clear();
1024 }
1025 }
1026
1027 /**
1028 * Returns a set view of the mappings contained in this map. The
1029 * set's iterator returns the mappings in descending key order.
1030 * Each element in the returned set is a <tt>Map.Entry</tt>. The
1031 * set is backed by this map, so changes to this map are reflected
1032 * in the set, and vice-versa. The set supports element removal,
1033 * which removes the corresponding mapping from the TreeMap,
1034 * through the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1035 * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
1036 * operations. It does not support the <tt>add</tt> or
1037 * <tt>addAll</tt> operations.
1038 *
1039 * @return a set view of the mappings contained in this map, in
1040 * descending key order
1041 * @see Map.Entry
1042 */
1043 public Set<Map.Entry<K,V>> descendingEntrySet() {
1044 Set<Map.Entry<K,V>> es = descendingEntrySet;
1045 return (es != null) ? es : (descendingEntrySet = new DescendingEntrySet());
1046 }
1047
1048 class DescendingEntrySet extends EntrySet {
1049 public Iterator<Map.Entry<K,V>> iterator() {
1050 return new DescendingEntryIterator(getLastEntry());
1051 }
1052 }
1053
1054 /**
1055 * Returns a Set view of the keys contained in this map. The
1056 * set's iterator will return the keys in descending order. The
1057 * map is backed by this <tt>TreeMap</tt> instance, so changes to
1058 * this map are reflected in the Set, and vice-versa. The Set
1059 * supports element removal, which removes the corresponding
1060 * mapping from the map, via the <tt>Iterator.remove</tt>,
1061 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>,
1062 * and <tt>clear</tt> operations. It does not support the
1063 * <tt>add</tt> or <tt>addAll</tt> operations.
1064 *
1065 * @return a set view of the keys contained in this TreeMap.
1066 */
1067 public Set<K> descendingKeySet() {
1068 Set<K> ks = descendingKeySet;
1069 return (ks != null) ? ks : (descendingKeySet = new DescendingKeySet());
1070 }
1071
1072 class DescendingKeySet extends KeySet {
1073 public Iterator<K> iterator() {
1074 return new DescendingKeyIterator(getLastEntry());
1075 }
1076 }
1077
1078 /**
1079 * Returns a view of the portion of this map whose keys range from
1080 * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive. (If
1081 * <tt>fromKey</tt> and <tt>toKey</tt> are equal, the returned
1082 * navigable map is empty.) The returned navigable map is backed
1083 * by this map, so changes in the returned navigable map are
1084 * reflected in this map, and vice-versa. The returned navigable
1085 * map supports all optional map operations.<p>
1086 *
1087 * The navigable map returned by this method will throw an
1088 * <tt>IllegalArgumentException</tt> if the user attempts to insert a key
1089 * less than <tt>fromKey</tt> or greater than or equal to
1090 * <tt>toKey</tt>.<p>
1091 *
1092 * Note: this method always returns a <i>half-open range</i> (which
1093 * includes its low endpoint but not its high endpoint). If you need a
1094 * <i>closed range</i> (which includes both endpoints), and the key type
1095 * allows for calculation of the successor of a given key, merely request the
1096 * subrange from <tt>lowEndpoint</tt> to <tt>successor(highEndpoint)</tt>.
1097 * For example, suppose that <tt>m</tt> is a navigable map whose keys are
1098 * strings. The following idiom obtains a view containing all of the
1099 * key-value mappings in <tt>m</tt> whose keys are between <tt>low</tt>
1100 * and <tt>high</tt>, inclusive:
1101 * <pre> NavigableMap sub = m.navigableSubMap(low, high+"\0");</pre>
1102 * A similar technique can be used to generate an <i>open range</i> (which
1103 * contains neither endpoint). The following idiom obtains a view
1104 * containing all of the key-value mappings in <tt>m</tt> whose keys are
1105 * between <tt>low</tt> and <tt>high</tt>, exclusive:
1106 * <pre> NavigableMap sub = m.navigableSubMap(low+"\0", high);</pre>
1107 *
1108 * @param fromKey low endpoint (inclusive) of the subMap.
1109 * @param toKey high endpoint (exclusive) of the subMap.
1110 *
1111 * @return a view of the portion of this map whose keys range from
1112 * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive.
1113 *
1114 * @throws ClassCastException if <tt>fromKey</tt> and <tt>toKey</tt>
1115 * cannot be compared to one another using this map's comparator
1116 * (or, if the map has no comparator, using natural ordering).
1117 * @throws IllegalArgumentException if <tt>fromKey</tt> is greater than
1118 * <tt>toKey</tt>.
1119 * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
1120 * <tt>null</tt> and this map uses natural order, or its
1121 * comparator does not tolerate <tt>null</tt> keys.
1122 */
1123 public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1124 return new SubMap(fromKey, toKey);
1125 }
1126
1127
1128 /**
1129 * Returns a view of the portion of this map whose keys are strictly less
1130 * than <tt>toKey</tt>. The returned navigable map is backed by this map, so
1131 * changes in the returned navigable map are reflected in this map, and
1132 * vice-versa. The returned navigable map supports all optional map
1133 * operations.<p>
1134 *
1135 * The navigable map returned by this method will throw an
1136 * <tt>IllegalArgumentException</tt> if the user attempts to insert a key
1137 * greater than or equal to <tt>toKey</tt>.<p>
1138 *
1139 * Note: this method always returns a view that does not contain its
1140 * (high) endpoint. If you need a view that does contain this endpoint,
1141 * and the key type allows for calculation of the successor of a given key,
1142 * merely request a headMap bounded by <tt>successor(highEndpoint)</tt>.
1143 * For example, suppose that suppose that <tt>m</tt> is a navigable map whose
1144 * keys are strings. The following idiom obtains a view containing all of
1145 * the key-value mappings in <tt>m</tt> whose keys are less than or equal
1146 * to <tt>high</tt>:
1147 * <pre>
1148 * NavigableMap head = m.navigableHeadMap(high+"\0");
1149 * </pre>
1150 *
1151 * @param toKey high endpoint (exclusive) of the headMap.
1152 * @return a view of the portion of this map whose keys are strictly
1153 * less than <tt>toKey</tt>.
1154 *
1155 * @throws ClassCastException if <tt>toKey</tt> is not compatible
1156 * with this map's comparator (or, if the map has no comparator,
1157 * if <tt>toKey</tt> does not implement <tt>Comparable</tt>).
1158 * @throws IllegalArgumentException if this map is itself a subMap,
1159 * headMap, or tailMap, and <tt>toKey</tt> is not within the
1160 * specified range of the subMap, headMap, or tailMap.
1161 * @throws NullPointerException if <tt>toKey</tt> is <tt>null</tt> and
1162 * this map uses natural order, or its comparator does not
1163 * tolerate <tt>null</tt> keys.
1164 */
1165 public NavigableMap<K,V> navigableHeadMap(K toKey) {
1166 return new SubMap(toKey, true);
1167 }
1168
1169 /**
1170 * Returns a view of the portion of this map whose keys are greater than
1171 * or equal to <tt>fromKey</tt>. The returned navigable map is backed by
1172 * this map, so changes in the returned navigable map are reflected in this
1173 * map, and vice-versa. The returned navigable map supports all optional map
1174 * operations.<p>
1175 *
1176 * The navigable map returned by this method will throw an
1177 * <tt>IllegalArgumentException</tt> if the user attempts to insert a key
1178 * less than <tt>fromKey</tt>.<p>
1179 *
1180 * Note: this method always returns a view that contains its (low)
1181 * endpoint. If you need a view that does not contain this endpoint, and
1182 * the element type allows for calculation of the successor of a given value,
1183 * merely request a tailMap bounded by <tt>successor(lowEndpoint)</tt>.
1184 * For example, suppose that <tt>m</tt> is a navigable map whose keys
1185 * are strings. The following idiom obtains a view containing
1186 * all of the key-value mappings in <tt>m</tt> whose keys are strictly
1187 * greater than <tt>low</tt>: <pre>
1188 * NavigableMap tail = m.navigableTailMap(low+"\0");
1189 * </pre>
1190 *
1191 * @param fromKey low endpoint (inclusive) of the tailMap.
1192 * @return a view of the portion of this map whose keys are greater
1193 * than or equal to <tt>fromKey</tt>.
1194 * @throws ClassCastException if <tt>fromKey</tt> is not compatible
1195 * with this map's comparator (or, if the map has no comparator,
1196 * if <tt>fromKey</tt> does not implement <tt>Comparable</tt>).
1197 * @throws IllegalArgumentException if this map is itself a subMap,
1198 * headMap, or tailMap, and <tt>fromKey</tt> is not within the
1199 * specified range of the subMap, headMap, or tailMap.
1200 * @throws NullPointerException if <tt>fromKey</tt> is <tt>null</tt> and
1201 * this map uses natural order, or its comparator does not
1202 * tolerate <tt>null</tt> keys.
1203 */
1204 public NavigableMap<K,V> navigableTailMap(K fromKey) {
1205 return new SubMap(fromKey, false);
1206 }
1207
1208 /**
1209 * Equivalent to <tt>navigableSubMap</tt> but with a return
1210 * type conforming to the <tt>SortedMap</tt> interface.
1211 * @param fromKey low endpoint (inclusive) of the subMap.
1212 * @param toKey high endpoint (exclusive) of the subMap.
1213 *
1214 * @return a view of the portion of this map whose keys range from
1215 * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive.
1216 *
1217 * @throws ClassCastException if <tt>fromKey</tt> and <tt>toKey</tt>
1218 * cannot be compared to one another using this map's comparator
1219 * (or, if the map has no comparator, using natural ordering).
1220 * @throws IllegalArgumentException if <tt>fromKey</tt> is greater than
1221 * <tt>toKey</tt>.
1222 * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
1223 * <tt>null</tt> and this map uses natural order, or its
1224 * comparator does not tolerate <tt>null</tt> keys.
1225 */
1226 public SortedMap<K,V> subMap(K fromKey, K toKey) {
1227 return new SubMap(fromKey, toKey);
1228 }
1229
1230
1231 /**
1232 * Equivalent to <tt>navigableHeadMap</tt> but with a return
1233 * type conforming to the <tt>SortedMap</tt> interface.
1234 *
1235 * @param toKey high endpoint (exclusive) of the headMap.
1236 * @return a view of the portion of this map whose keys are strictly
1237 * less than <tt>toKey</tt>.
1238 *
1239 * @throws ClassCastException if <tt>toKey</tt> is not compatible
1240 * with this map's comparator (or, if the map has no comparator,
1241 * if <tt>toKey</tt> does not implement <tt>Comparable</tt>).
1242 * @throws IllegalArgumentException if this map is itself a subMap,
1243 * headMap, or tailMap, and <tt>toKey</tt> is not within the
1244 * specified range of the subMap, headMap, or tailMap.
1245 * @throws NullPointerException if <tt>toKey</tt> is <tt>null</tt> and
1246 * this map uses natural order, or its comparator does not
1247 * tolerate <tt>null</tt> keys.
1248 */
1249 public SortedMap<K,V> headMap(K toKey) {
1250 return new SubMap(toKey, true);
1251 }
1252
1253 /**
1254 * Equivalent to <tt>navigableTailMap</tt> but with a return
1255 * type conforming to the <tt>SortedMap</tt> interface.
1256 *
1257 * @param fromKey low endpoint (inclusive) of the tailMap.
1258 * @return a view of the portion of this map whose keys are greater
1259 * than or equal to <tt>fromKey</tt>.
1260 * @throws ClassCastException if <tt>fromKey</tt> is not compatible
1261 * with this map's comparator (or, if the map has no comparator,
1262 * if <tt>fromKey</tt> does not implement <tt>Comparable</tt>).
1263 * @throws IllegalArgumentException if this map is itself a subMap,
1264 * headMap, or tailMap, and <tt>fromKey</tt> is not within the
1265 * specified range of the subMap, headMap, or tailMap.
1266 * @throws NullPointerException if <tt>fromKey</tt> is <tt>null</tt> and
1267 * this map uses natural order, or its comparator does not
1268 * tolerate <tt>null</tt> keys.
1269 */
1270 public SortedMap<K,V> tailMap(K fromKey) {
1271 return new SubMap(fromKey, false);
1272 }
1273
1274 private class SubMap
1275 extends AbstractMap<K,V>
1276 implements NavigableMap<K,V>, java.io.Serializable {
1277 private static final long serialVersionUID = -6520786458950516097L;
1278
1279 /**
1280 * fromKey is significant only if fromStart is false. Similarly,
1281 * toKey is significant only if toStart is false.
1282 */
1283 private boolean fromStart = false, toEnd = false;
1284 private K fromKey, toKey;
1285
1286 SubMap(K fromKey, K toKey) {
1287 if (compare(fromKey, toKey) > 0)
1288 throw new IllegalArgumentException("fromKey > toKey");
1289 this.fromKey = fromKey;
1290 this.toKey = toKey;
1291 }
1292
1293 SubMap(K key, boolean headMap) {
1294 compare(key, key); // Type-check key
1295
1296 if (headMap) {
1297 fromStart = true;
1298 toKey = key;
1299 } else {
1300 toEnd = true;
1301 fromKey = key;
1302 }
1303 }
1304
1305 SubMap(boolean fromStart, K fromKey, boolean toEnd, K toKey) {
1306 this.fromStart = fromStart;
1307 this.fromKey= fromKey;
1308 this.toEnd = toEnd;
1309 this.toKey = toKey;
1310 }
1311
1312 public boolean isEmpty() {
1313 return entrySet().isEmpty();
1314 }
1315
1316 public boolean containsKey(Object key) {
1317 return inRange((K) key) && TreeMap.this.containsKey(key);
1318 }
1319
1320 public V get(Object key) {
1321 if (!inRange((K) key))
1322 return null;
1323 return TreeMap.this.get(key);
1324 }
1325
1326 public V put(K key, V value) {
1327 if (!inRange(key))
1328 throw new IllegalArgumentException("key out of range");
1329 return TreeMap.this.put(key, value);
1330 }
1331
1332 public V remove(Object key) {
1333 if (!inRange((K) key))
1334 return null;
1335 return TreeMap.this.remove(key);
1336 }
1337
1338 public Comparator<? super K> comparator() {
1339 return comparator;
1340 }
1341
1342 public K firstKey() {
1343 TreeMap.Entry<K,V> e = fromStart ? getFirstEntry() : getCeilingEntry(fromKey);
1344 K first = key(e);
1345 if (!toEnd && compare(first, toKey) >= 0)
1346 throw new NoSuchElementException();
1347 return first;
1348 }
1349
1350 public K lastKey() {
1351 TreeMap.Entry<K,V> e = toEnd ? getLastEntry() : getLowerEntry(toKey);
1352 K last = key(e);
1353 if (!fromStart && compare(last, fromKey) < 0)
1354 throw new NoSuchElementException();
1355 return last;
1356 }
1357
1358 public Map.Entry<K,V> firstEntry() {
1359 TreeMap.Entry<K,V> e = fromStart ?
1360 getFirstEntry() : getCeilingEntry(fromKey);
1361 if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1362 return null;
1363 return e;
1364 }
1365
1366 public Map.Entry<K,V> lastEntry() {
1367 TreeMap.Entry<K,V> e = toEnd ?
1368 getLastEntry() : getLowerEntry(toKey);
1369 if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1370 return null;
1371 return e;
1372 }
1373
1374 public Map.Entry<K,V> pollFirstEntry() {
1375 TreeMap.Entry<K,V> e = fromStart ?
1376 getFirstEntry() : getCeilingEntry(fromKey);
1377 if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1378 return null;
1379 Map.Entry result = new AbstractMap.SimpleImmutableEntry(e);
1380 deleteEntry(e);
1381 return result;
1382 }
1383
1384 public Map.Entry<K,V> pollLastEntry() {
1385 TreeMap.Entry<K,V> e = toEnd ?
1386 getLastEntry() : getLowerEntry(toKey);
1387 if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1388 return null;
1389 Map.Entry result = new AbstractMap.SimpleImmutableEntry(e);
1390 deleteEntry(e);
1391 return result;
1392 }
1393
1394 private TreeMap.Entry<K,V> subceiling(K key) {
1395 TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1396 getCeilingEntry(fromKey) : getCeilingEntry(key);
1397 if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1398 return null;
1399 return e;
1400 }
1401
1402 public Map.Entry<K,V> ceilingEntry(K key) {
1403 TreeMap.Entry<K,V> e = subceiling(key);
1404 return e == null? null : new AbstractMap.SimpleImmutableEntry(e);
1405 }
1406
1407 public K ceilingKey(K key) {
1408 TreeMap.Entry<K,V> e = subceiling(key);
1409 return e == null? null : e.key;
1410 }
1411
1412
1413 private TreeMap.Entry<K,V> subhigher(K key) {
1414 TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1415 getCeilingEntry(fromKey) : getHigherEntry(key);
1416 if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1417 return null;
1418 return e;
1419 }
1420
1421 public Map.Entry<K,V> higherEntry(K key) {
1422 TreeMap.Entry<K,V> e = subhigher(key);
1423 return e == null? null : new AbstractMap.SimpleImmutableEntry(e);
1424 }
1425
1426 public K higherKey(K key) {
1427 TreeMap.Entry<K,V> e = subhigher(key);
1428 return e == null? null : e.key;
1429 }
1430
1431 private TreeMap.Entry<K,V> subfloor(K key) {
1432 TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1433 getLowerEntry(toKey) : getFloorEntry(key);
1434 if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1435 return null;
1436 return e;
1437 }
1438
1439 public Map.Entry<K,V> floorEntry(K key) {
1440 TreeMap.Entry<K,V> e = subfloor(key);
1441 return e == null? null : new AbstractMap.SimpleImmutableEntry(e);
1442 }
1443
1444 public K floorKey(K key) {
1445 TreeMap.Entry<K,V> e = subfloor(key);
1446 return e == null? null : e.key;
1447 }
1448
1449 private TreeMap.Entry<K,V> sublower(K key) {
1450 TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1451 getLowerEntry(toKey) : getLowerEntry(key);
1452 if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1453 return null;
1454 return e;
1455 }
1456
1457 public Map.Entry<K,V> lowerEntry(K key) {
1458 TreeMap.Entry<K,V> e = sublower(key);
1459 return e == null? null : new AbstractMap.SimpleImmutableEntry(e);
1460 }
1461
1462 public K lowerKey(K key) {
1463 TreeMap.Entry<K,V> e = sublower(key);
1464 return e == null? null : e.key;
1465 }
1466
1467 private transient Set<Map.Entry<K,V>> entrySet = null;
1468
1469 public Set<Map.Entry<K,V>> entrySet() {
1470 Set<Map.Entry<K,V>> es = entrySet;
1471 return (es != null)? es : (entrySet = new EntrySetView());
1472 }
1473
1474 private class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1475 private transient int size = -1, sizeModCount;
1476
1477 public int size() {
1478 if (size == -1 || sizeModCount != TreeMap.this.modCount) {
1479 size = 0; sizeModCount = TreeMap.this.modCount;
1480 Iterator i = iterator();
1481 while (i.hasNext()) {
1482 size++;
1483 i.next();
1484 }
1485 }
1486 return size;
1487 }
1488
1489 public boolean isEmpty() {
1490 return !iterator().hasNext();
1491 }
1492
1493 public boolean contains(Object o) {
1494 if (!(o instanceof Map.Entry))
1495 return false;
1496 Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1497 K key = entry.getKey();
1498 if (!inRange(key))
1499 return false;
1500 TreeMap.Entry node = getEntry(key);
1501 return node != null &&
1502 valEquals(node.getValue(), entry.getValue());
1503 }
1504
1505 public boolean remove(Object o) {
1506 if (!(o instanceof Map.Entry))
1507 return false;
1508 Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1509 K key = entry.getKey();
1510 if (!inRange(key))
1511 return false;
1512 TreeMap.Entry<K,V> node = getEntry(key);
1513 if (node!=null && valEquals(node.getValue(),entry.getValue())){
1514 deleteEntry(node);
1515 return true;
1516 }
1517 return false;
1518 }
1519
1520 public Iterator<Map.Entry<K,V>> iterator() {
1521 return new SubMapEntryIterator(
1522 (fromStart ? getFirstEntry() : getCeilingEntry(fromKey)),
1523 (toEnd ? null : getCeilingEntry(toKey)));
1524 }
1525 }
1526
1527 private transient Set<Map.Entry<K,V>> descendingEntrySetView = null;
1528 private transient Set<K> descendingKeySetView = null;
1529
1530 public Set<Map.Entry<K,V>> descendingEntrySet() {
1531 Set<Map.Entry<K,V>> es = descendingEntrySetView;
1532 return (es != null) ? es : (descendingEntrySetView = new DescendingEntrySetView());
1533 }
1534
1535 public Set<K> descendingKeySet() {
1536 Set<K> ks = descendingKeySetView;
1537 return (ks != null) ? ks : (descendingKeySetView = new DescendingKeySetView());
1538 }
1539
1540 private class DescendingEntrySetView extends EntrySetView {
1541 public Iterator<Map.Entry<K,V>> iterator() {
1542 return new DescendingSubMapEntryIterator
1543 ((toEnd ? getLastEntry() : getLowerEntry(toKey)),
1544 (fromStart ? null : getLowerEntry(fromKey)));
1545 }
1546 }
1547
1548 private class DescendingKeySetView extends AbstractSet<K> {
1549 public Iterator<K> iterator() {
1550 return new Iterator<K>() {
1551 private Iterator<Entry<K,V>> i = descendingEntrySet().iterator();
1552
1553 public boolean hasNext() { return i.hasNext(); }
1554 public K next() { return i.next().getKey(); }
1555 public void remove() { i.remove(); }
1556 };
1557 }
1558
1559 public int size() {
1560 return SubMap.this.size();
1561 }
1562
1563 public boolean contains(Object k) {
1564 return SubMap.this.containsKey(k);
1565 }
1566 }
1567
1568
1569 public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1570 if (!inRange2(fromKey))
1571 throw new IllegalArgumentException("fromKey out of range");
1572 if (!inRange2(toKey))
1573 throw new IllegalArgumentException("toKey out of range");
1574 return new SubMap(fromKey, toKey);
1575 }
1576
1577 public NavigableMap<K,V> navigableHeadMap(K toKey) {
1578 if (!inRange2(toKey))
1579 throw new IllegalArgumentException("toKey out of range");
1580 return new SubMap(fromStart, fromKey, false, toKey);
1581 }
1582
1583 public NavigableMap<K,V> navigableTailMap(K fromKey) {
1584 if (!inRange2(fromKey))
1585 throw new IllegalArgumentException("fromKey out of range");
1586 return new SubMap(false, fromKey, toEnd, toKey);
1587 }
1588
1589
1590 public SortedMap<K,V> subMap(K fromKey, K toKey) {
1591 return navigableSubMap(fromKey, toKey);
1592 }
1593
1594 public SortedMap<K,V> headMap(K toKey) {
1595 return navigableHeadMap(toKey);
1596 }
1597
1598 public SortedMap<K,V> tailMap(K fromKey) {
1599 return navigableTailMap(fromKey);
1600 }
1601
1602 private boolean inRange(K key) {
1603 return (fromStart || compare(key, fromKey) >= 0) &&
1604 (toEnd || compare(key, toKey) < 0);
1605 }
1606
1607 // This form allows the high endpoint (as well as all legit keys)
1608 private boolean inRange2(K key) {
1609 return (fromStart || compare(key, fromKey) >= 0) &&
1610 (toEnd || compare(key, toKey) <= 0);
1611 }
1612 }
1613
1614 /**
1615 * TreeMap Iterator.
1616 */
1617 abstract class PrivateEntryIterator<T> implements Iterator<T> {
1618 int expectedModCount = TreeMap.this.modCount;
1619 Entry<K,V> lastReturned = null;
1620 Entry<K,V> next;
1621
1622 PrivateEntryIterator(Entry<K,V> first) {
1623 next = first;
1624 }
1625
1626 public boolean hasNext() {
1627 return next != null;
1628 }
1629
1630 Entry<K,V> nextEntry() {
1631 if (next == null)
1632 throw new NoSuchElementException();
1633 if (modCount != expectedModCount)
1634 throw new ConcurrentModificationException();
1635 lastReturned = next;
1636 next = successor(next);
1637 return lastReturned;
1638 }
1639
1640 public void remove() {
1641 if (lastReturned == null)
1642 throw new IllegalStateException();
1643 if (modCount != expectedModCount)
1644 throw new ConcurrentModificationException();
1645 if (lastReturned.left != null && lastReturned.right != null)
1646 next = lastReturned;
1647 deleteEntry(lastReturned);
1648 expectedModCount++;
1649 lastReturned = null;
1650 }
1651 }
1652
1653 class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1654 EntryIterator(Entry<K,V> first) {
1655 super(first);
1656 }
1657
1658 public Map.Entry<K,V> next() {
1659 return nextEntry();
1660 }
1661 }
1662
1663 class KeyIterator extends PrivateEntryIterator<K> {
1664 KeyIterator(Entry<K,V> first) {
1665 super(first);
1666 }
1667 public K next() {
1668 return nextEntry().key;
1669 }
1670 }
1671
1672 class ValueIterator extends PrivateEntryIterator<V> {
1673 ValueIterator(Entry<K,V> first) {
1674 super(first);
1675 }
1676 public V next() {
1677 return nextEntry().value;
1678 }
1679 }
1680
1681 class SubMapEntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1682 private final K firstExcludedKey;
1683
1684 SubMapEntryIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1685 super(first);
1686 firstExcludedKey = (firstExcluded == null
1687 ? null
1688 : firstExcluded.key);
1689 }
1690
1691 public boolean hasNext() {
1692 return next != null && next.key != firstExcludedKey;
1693 }
1694
1695 public Map.Entry<K,V> next() {
1696 if (next == null || next.key == firstExcludedKey)
1697 throw new NoSuchElementException();
1698 return nextEntry();
1699 }
1700 }
1701
1702
1703 /**
1704 * Base for Descending Iterators.
1705 */
1706 abstract class DescendingPrivateEntryIterator<T> extends PrivateEntryIterator<T> {
1707 DescendingPrivateEntryIterator(Entry<K,V> first) {
1708 super(first);
1709 }
1710
1711 Entry<K,V> nextEntry() {
1712 if (next == null)
1713 throw new NoSuchElementException();
1714 if (modCount != expectedModCount)
1715 throw new ConcurrentModificationException();
1716 lastReturned = next;
1717 next = predecessor(next);
1718 return lastReturned;
1719 }
1720 }
1721
1722 class DescendingEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1723 DescendingEntryIterator(Entry<K,V> first) {
1724 super(first);
1725 }
1726 public Map.Entry<K,V> next() {
1727 return nextEntry();
1728 }
1729 }
1730
1731 class DescendingKeyIterator extends DescendingPrivateEntryIterator<K> {
1732 DescendingKeyIterator(Entry<K,V> first) {
1733 super(first);
1734 }
1735 public K next() {
1736 return nextEntry().key;
1737 }
1738 }
1739
1740
1741 class DescendingSubMapEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1742 private final K lastExcludedKey;
1743
1744 DescendingSubMapEntryIterator(Entry<K,V> last, Entry<K,V> lastExcluded) {
1745 super(last);
1746 lastExcludedKey = (lastExcluded == null
1747 ? null
1748 : lastExcluded.key);
1749 }
1750
1751 public boolean hasNext() {
1752 return next != null && next.key != lastExcludedKey;
1753 }
1754
1755 public Map.Entry<K,V> next() {
1756 if (next == null || next.key == lastExcludedKey)
1757 throw new NoSuchElementException();
1758 return nextEntry();
1759 }
1760
1761 }
1762
1763
1764 /**
1765 * Compares two keys using the correct comparison method for this TreeMap.
1766 */
1767 private int compare(K k1, K k2) {
1768 return comparator==null ? ((Comparable<? super K>)k1).compareTo(k2)
1769 : comparator.compare(k1, k2);
1770 }
1771
1772 /**
1773 * Test two values for equality. Differs from o1.equals(o2) only in
1774 * that it copes with <tt>null</tt> o1 properly.
1775 */
1776 private static boolean valEquals(Object o1, Object o2) {
1777 return (o1==null ? o2==null : o1.equals(o2));
1778 }
1779
1780 private static final boolean RED = false;
1781 private static final boolean BLACK = true;
1782
1783 /**
1784 * Node in the Tree. Doubles as a means to pass key-value pairs back to
1785 * user (see Map.Entry).
1786 */
1787
1788 static class Entry<K,V> implements Map.Entry<K,V> {
1789 K key;
1790 V value;
1791 Entry<K,V> left = null;
1792 Entry<K,V> right = null;
1793 Entry<K,V> parent;
1794 boolean color = BLACK;
1795
1796 /**
1797 * Make a new cell with given key, value, and parent, and with
1798 * <tt>null</tt> child links, and BLACK color.
1799 */
1800 Entry(K key, V value, Entry<K,V> parent) {
1801 this.key = key;
1802 this.value = value;
1803 this.parent = parent;
1804 }
1805
1806 /**
1807 * Returns the key.
1808 *
1809 * @return the key.
1810 */
1811 public K getKey() {
1812 return key;
1813 }
1814
1815 /**
1816 * Returns the value associated with the key.
1817 *
1818 * @return the value associated with the key.
1819 */
1820 public V getValue() {
1821 return value;
1822 }
1823
1824 /**
1825 * Replaces the value currently associated with the key with the given
1826 * value.
1827 *
1828 * @return the value associated with the key before this method was
1829 * called.
1830 */
1831 public V setValue(V value) {
1832 V oldValue = this.value;
1833 this.value = value;
1834 return oldValue;
1835 }
1836
1837 public boolean equals(Object o) {
1838 if (!(o instanceof Map.Entry))
1839 return false;
1840 Map.Entry e = (Map.Entry)o;
1841
1842 return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
1843 }
1844
1845 public int hashCode() {
1846 int keyHash = (key==null ? 0 : key.hashCode());
1847 int valueHash = (value==null ? 0 : value.hashCode());
1848 return keyHash ^ valueHash;
1849 }
1850
1851 public String toString() {
1852 return key + "=" + value;
1853 }
1854 }
1855
1856 /**
1857 * Returns the first Entry in the TreeMap (according to the TreeMap's
1858 * key-sort function). Returns null if the TreeMap is empty.
1859 */
1860 private Entry<K,V> getFirstEntry() {
1861 Entry<K,V> p = root;
1862 if (p != null)
1863 while (p.left != null)
1864 p = p.left;
1865 return p;
1866 }
1867
1868 /**
1869 * Returns the last Entry in the TreeMap (according to the TreeMap's
1870 * key-sort function). Returns null if the TreeMap is empty.
1871 */
1872 private Entry<K,V> getLastEntry() {
1873 Entry<K,V> p = root;
1874 if (p != null)
1875 while (p.right != null)
1876 p = p.right;
1877 return p;
1878 }
1879
1880 /**
1881 * Returns the successor of the specified Entry, or null if no such.
1882 */
1883 private Entry<K,V> successor(Entry<K,V> t) {
1884 if (t == null)
1885 return null;
1886 else if (t.right != null) {
1887 Entry<K,V> p = t.right;
1888 while (p.left != null)
1889 p = p.left;
1890 return p;
1891 } else {
1892 Entry<K,V> p = t.parent;
1893 Entry<K,V> ch = t;
1894 while (p != null && ch == p.right) {
1895 ch = p;
1896 p = p.parent;
1897 }
1898 return p;
1899 }
1900 }
1901
1902 /**
1903 * Returns the predecessor of the specified Entry, or null if no such.
1904 */
1905 private Entry<K,V> predecessor(Entry<K,V> t) {
1906 if (t == null)
1907 return null;
1908 else if (t.left != null) {
1909 Entry<K,V> p = t.left;
1910 while (p.right != null)
1911 p = p.right;
1912 return p;
1913 } else {
1914 Entry<K,V> p = t.parent;
1915 Entry<K,V> ch = t;
1916 while (p != null && ch == p.left) {
1917 ch = p;
1918 p = p.parent;
1919 }
1920 return p;
1921 }
1922 }
1923
1924 /**
1925 * Balancing operations.
1926 *
1927 * Implementations of rebalancings during insertion and deletion are
1928 * slightly different than the CLR version. Rather than using dummy
1929 * nilnodes, we use a set of accessors that deal properly with null. They
1930 * are used to avoid messiness surrounding nullness checks in the main
1931 * algorithms.
1932 */
1933
1934 private static <K,V> boolean colorOf(Entry<K,V> p) {
1935 return (p == null ? BLACK : p.color);
1936 }
1937
1938 private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) {
1939 return (p == null ? null: p.parent);
1940 }
1941
1942 private static <K,V> void setColor(Entry<K,V> p, boolean c) {
1943 if (p != null)
1944 p.color = c;
1945 }
1946
1947 private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) {
1948 return (p == null) ? null: p.left;
1949 }
1950
1951 private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) {
1952 return (p == null) ? null: p.right;
1953 }
1954
1955 /** From CLR **/
1956 private void rotateLeft(Entry<K,V> p) {
1957 Entry<K,V> r = p.right;
1958 p.right = r.left;
1959 if (r.left != null)
1960 r.left.parent = p;
1961 r.parent = p.parent;
1962 if (p.parent == null)
1963 root = r;
1964 else if (p.parent.left == p)
1965 p.parent.left = r;
1966 else
1967 p.parent.right = r;
1968 r.left = p;
1969 p.parent = r;
1970 }
1971
1972 /** From CLR **/
1973 private void rotateRight(Entry<K,V> p) {
1974 Entry<K,V> l = p.left;
1975 p.left = l.right;
1976 if (l.right != null) l.right.parent = p;
1977 l.parent = p.parent;
1978 if (p.parent == null)
1979 root = l;
1980 else if (p.parent.right == p)
1981 p.parent.right = l;
1982 else p.parent.left = l;
1983 l.right = p;
1984 p.parent = l;
1985 }
1986
1987
1988 /** From CLR **/
1989 private void fixAfterInsertion(Entry<K,V> x) {
1990 x.color = RED;
1991
1992 while (x != null && x != root && x.parent.color == RED) {
1993 if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
1994 Entry<K,V> y = rightOf(parentOf(parentOf(x)));
1995 if (colorOf(y) == RED) {
1996 setColor(parentOf(x), BLACK);
1997 setColor(y, BLACK);
1998 setColor(parentOf(parentOf(x)), RED);
1999 x = parentOf(parentOf(x));
2000 } else {
2001 if (x == rightOf(parentOf(x))) {
2002 x = parentOf(x);
2003 rotateLeft(x);
2004 }
2005 setColor(parentOf(x), BLACK);
2006 setColor(parentOf(parentOf(x)), RED);
2007 if (parentOf(parentOf(x)) != null)
2008 rotateRight(parentOf(parentOf(x)));
2009 }
2010 } else {
2011 Entry<K,V> y = leftOf(parentOf(parentOf(x)));
2012 if (colorOf(y) == RED) {
2013 setColor(parentOf(x), BLACK);
2014 setColor(y, BLACK);
2015 setColor(parentOf(parentOf(x)), RED);
2016 x = parentOf(parentOf(x));
2017 } else {
2018 if (x == leftOf(parentOf(x))) {
2019 x = parentOf(x);
2020 rotateRight(x);
2021 }
2022 setColor(parentOf(x), BLACK);
2023 setColor(parentOf(parentOf(x)), RED);
2024 if (parentOf(parentOf(x)) != null)
2025 rotateLeft(parentOf(parentOf(x)));
2026 }
2027 }
2028 }
2029 root.color = BLACK;
2030 }
2031
2032 /**
2033 * Delete node p, and then rebalance the tree.
2034 */
2035
2036 private void deleteEntry(Entry<K,V> p) {
2037 decrementSize();
2038
2039 // If strictly internal, copy successor's element to p and then make p
2040 // point to successor.
2041 if (p.left != null && p.right != null) {
2042 Entry<K,V> s = successor (p);
2043 p.key = s.key;
2044 p.value = s.value;
2045 p = s;
2046 } // p has 2 children
2047
2048 // Start fixup at replacement node, if it exists.
2049 Entry<K,V> replacement = (p.left != null ? p.left : p.right);
2050
2051 if (replacement != null) {
2052 // Link replacement to parent
2053 replacement.parent = p.parent;
2054 if (p.parent == null)
2055 root = replacement;
2056 else if (p == p.parent.left)
2057 p.parent.left = replacement;
2058 else
2059 p.parent.right = replacement;
2060
2061 // Null out links so they are OK to use by fixAfterDeletion.
2062 p.left = p.right = p.parent = null;
2063
2064 // Fix replacement
2065 if (p.color == BLACK)
2066 fixAfterDeletion(replacement);
2067 } else if (p.parent == null) { // return if we are the only node.
2068 root = null;
2069 } else { // No children. Use self as phantom replacement and unlink.
2070 if (p.color == BLACK)
2071 fixAfterDeletion(p);
2072
2073 if (p.parent != null) {
2074 if (p == p.parent.left)
2075 p.parent.left = null;
2076 else if (p == p.parent.right)
2077 p.parent.right = null;
2078 p.parent = null;
2079 }
2080 }
2081 }
2082
2083 /** From CLR **/
2084 private void fixAfterDeletion(Entry<K,V> x) {
2085 while (x != root && colorOf(x) == BLACK) {
2086 if (x == leftOf(parentOf(x))) {
2087 Entry<K,V> sib = rightOf(parentOf(x));
2088
2089 if (colorOf(sib) == RED) {
2090 setColor(sib, BLACK);
2091 setColor(parentOf(x), RED);
2092 rotateLeft(parentOf(x));
2093 sib = rightOf(parentOf(x));
2094 }
2095
2096 if (colorOf(leftOf(sib)) == BLACK &&
2097 colorOf(rightOf(sib)) == BLACK) {
2098 setColor(sib, RED);
2099 x = parentOf(x);
2100 } else {
2101 if (colorOf(rightOf(sib)) == BLACK) {
2102 setColor(leftOf(sib), BLACK);
2103 setColor(sib, RED);
2104 rotateRight(sib);
2105 sib = rightOf(parentOf(x));
2106 }
2107 setColor(sib, colorOf(parentOf(x)));
2108 setColor(parentOf(x), BLACK);
2109 setColor(rightOf(sib), BLACK);
2110 rotateLeft(parentOf(x));
2111 x = root;
2112 }
2113 } else { // symmetric
2114 Entry<K,V> sib = leftOf(parentOf(x));
2115
2116 if (colorOf(sib) == RED) {
2117 setColor(sib, BLACK);
2118 setColor(parentOf(x), RED);
2119 rotateRight(parentOf(x));
2120 sib = leftOf(parentOf(x));
2121 }
2122
2123 if (colorOf(rightOf(sib)) == BLACK &&
2124 colorOf(leftOf(sib)) == BLACK) {
2125 setColor(sib, RED);
2126 x = parentOf(x);
2127 } else {
2128 if (colorOf(leftOf(sib)) == BLACK) {
2129 setColor(rightOf(sib), BLACK);
2130 setColor(sib, RED);
2131 rotateLeft(sib);
2132 sib = leftOf(parentOf(x));
2133 }
2134 setColor(sib, colorOf(parentOf(x)));
2135 setColor(parentOf(x), BLACK);
2136 setColor(leftOf(sib), BLACK);
2137 rotateRight(parentOf(x));
2138 x = root;
2139 }
2140 }
2141 }
2142
2143 setColor(x, BLACK);
2144 }
2145
2146 private static final long serialVersionUID = 919286545866124006L;
2147
2148 /**
2149 * Save the state of the <tt>TreeMap</tt> instance to a stream (i.e.,
2150 * serialize it).
2151 *
2152 * @serialData The <i>size</i> of the TreeMap (the number of key-value
2153 * mappings) is emitted (int), followed by the key (Object)
2154 * and value (Object) for each key-value mapping represented
2155 * by the TreeMap. The key-value mappings are emitted in
2156 * key-order (as determined by the TreeMap's Comparator,
2157 * or by the keys' natural ordering if the TreeMap has no
2158 * Comparator).
2159 */
2160 private void writeObject(java.io.ObjectOutputStream s)
2161 throws java.io.IOException {
2162 // Write out the Comparator and any hidden stuff
2163 s.defaultWriteObject();
2164
2165 // Write out size (number of Mappings)
2166 s.writeInt(size);
2167
2168 Set<Map.Entry<K,V>> es = entrySet();
2169 // Write out keys and values (alternating)
2170 for (Iterator<Map.Entry<K,V>> i = es.iterator(); i.hasNext(); ) {
2171 Map.Entry<K,V> e = i.next();
2172 s.writeObject(e.getKey());
2173 s.writeObject(e.getValue());
2174 }
2175 }
2176
2177
2178
2179 /**
2180 * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e.,
2181 * deserialize it).
2182 */
2183 private void readObject(final java.io.ObjectInputStream s)
2184 throws java.io.IOException, ClassNotFoundException {
2185 // Read in the Comparator and any hidden stuff
2186 s.defaultReadObject();
2187
2188 // Read in size
2189 int size = s.readInt();
2190
2191 buildFromSorted(size, null, s, null);
2192 }
2193
2194 /** Intended to be called only from TreeSet.readObject **/
2195 void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2196 throws java.io.IOException, ClassNotFoundException {
2197 buildFromSorted(size, null, s, defaultVal);
2198 }
2199
2200 /** Intended to be called only from TreeSet.addAll **/
2201 void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2202 try {
2203 buildFromSorted(set.size(), set.iterator(), null, defaultVal);
2204 } catch (java.io.IOException cannotHappen) {
2205 } catch (ClassNotFoundException cannotHappen) {
2206 }
2207 }
2208
2209
2210 /**
2211 * Linear time tree building algorithm from sorted data. Can accept keys
2212 * and/or values from iterator or stream. This leads to too many
2213 * parameters, but seems better than alternatives. The four formats
2214 * that this method accepts are:
2215 *
2216 * 1) An iterator of Map.Entries. (it != null, defaultVal == null).
2217 * 2) An iterator of keys. (it != null, defaultVal != null).
2218 * 3) A stream of alternating serialized keys and values.
2219 * (it == null, defaultVal == null).
2220 * 4) A stream of serialized keys. (it == null, defaultVal != null).
2221 *
2222 * It is assumed that the comparator of the TreeMap is already set prior
2223 * to calling this method.
2224 *
2225 * @param size the number of keys (or key-value pairs) to be read from
2226 * the iterator or stream.
2227 * @param it If non-null, new entries are created from entries
2228 * or keys read from this iterator.
2229 * @param str If non-null, new entries are created from keys and
2230 * possibly values read from this stream in serialized form.
2231 * Exactly one of it and str should be non-null.
2232 * @param defaultVal if non-null, this default value is used for
2233 * each value in the map. If null, each value is read from
2234 * iterator or stream, as described above.
2235 * @throws IOException propagated from stream reads. This cannot
2236 * occur if str is null.
2237 * @throws ClassNotFoundException propagated from readObject.
2238 * This cannot occur if str is null.
2239 */
2240 private
2241 void buildFromSorted(int size, Iterator it,
2242 java.io.ObjectInputStream str,
2243 V defaultVal)
2244 throws java.io.IOException, ClassNotFoundException {
2245 this.size = size;
2246 root =
2247 buildFromSorted(0, 0, size-1, computeRedLevel(size),
2248 it, str, defaultVal);
2249 }
2250
2251 /**
2252 * Recursive "helper method" that does the real work of the
2253 * of the previous method. Identically named parameters have
2254 * identical definitions. Additional parameters are documented below.
2255 * It is assumed that the comparator and size fields of the TreeMap are
2256 * already set prior to calling this method. (It ignores both fields.)
2257 *
2258 * @param level the current level of tree. Initial call should be 0.
2259 * @param lo the first element index of this subtree. Initial should be 0.
2260 * @param hi the last element index of this subtree. Initial should be
2261 * size-1.
2262 * @param redLevel the level at which nodes should be red.
2263 * Must be equal to computeRedLevel for tree of this size.
2264 */
2265 private final Entry<K,V> buildFromSorted(int level, int lo, int hi,
2266 int redLevel,
2267 Iterator it,
2268 java.io.ObjectInputStream str,
2269 V defaultVal)
2270 throws java.io.IOException, ClassNotFoundException {
2271 /*
2272 * Strategy: The root is the middlemost element. To get to it, we
2273 * have to first recursively construct the entire left subtree,
2274 * so as to grab all of its elements. We can then proceed with right
2275 * subtree.
2276 *
2277 * The lo and hi arguments are the minimum and maximum
2278 * indices to pull out of the iterator or stream for current subtree.
2279 * They are not actually indexed, we just proceed sequentially,
2280 * ensuring that items are extracted in corresponding order.
2281 */
2282
2283 if (hi < lo) return null;
2284
2285 int mid = (lo + hi) / 2;
2286
2287 Entry<K,V> left = null;
2288 if (lo < mid)
2289 left = buildFromSorted(level+1, lo, mid - 1, redLevel,
2290 it, str, defaultVal);
2291
2292 // extract key and/or value from iterator or stream
2293 K key;
2294 V value;
2295 if (it != null) {
2296 if (defaultVal==null) {
2297 Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
2298 key = entry.getKey();
2299 value = entry.getValue();
2300 } else {
2301 key = (K)it.next();
2302 value = defaultVal;
2303 }
2304 } else { // use stream
2305 key = (K) str.readObject();
2306 value = (defaultVal != null ? defaultVal : (V) str.readObject());
2307 }
2308
2309 Entry<K,V> middle = new Entry<K,V>(key, value, null);
2310
2311 // color nodes in non-full bottommost level red
2312 if (level == redLevel)
2313 middle.color = RED;
2314
2315 if (left != null) {
2316 middle.left = left;
2317 left.parent = middle;
2318 }
2319
2320 if (mid < hi) {
2321 Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
2322 it, str, defaultVal);
2323 middle.right = right;
2324 right.parent = middle;
2325 }
2326
2327 return middle;
2328 }
2329
2330 /**
2331 * Find the level down to which to assign all nodes BLACK. This is the
2332 * last `full' level of the complete binary tree produced by
2333 * buildTree. The remaining nodes are colored RED. (This makes a `nice'
2334 * set of color assignments wrt future insertions.) This level number is
2335 * computed by finding the number of splits needed to reach the zeroeth
2336 * node. (The answer is ~lg(N), but in any case must be computed by same
2337 * quick O(lg(N)) loop.)
2338 */
2339 private static int computeRedLevel(int sz) {
2340 int level = 0;
2341 for (int m = sz - 1; m >= 0; m = m / 2 - 1)
2342 level++;
2343 return level;
2344 }
2345
2346 }