ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
Revision: 1.27
Committed: Sun Mar 19 18:03:54 2006 UTC (18 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.26: +6 -8 lines
Log Message:
sync with Mustang

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