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