ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.30
Committed: Thu Apr 20 21:49:36 2006 UTC (18 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.29: +38 -38 lines
Log Message:
whitespace

File Contents

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