ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.18
Committed: Thu Jun 16 02:11:13 2005 UTC (18 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.17: +2 -1 lines
Log Message:
whitespace

File Contents

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