1 /*
   2  * Copyright (c) 1997, 2014, 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 
  26 package java.util;
  27 
  28 import java.io.Serializable;
  29 import java.util.function.BiConsumer;
  30 import java.util.function.BiFunction;
  31 import java.util.function.Consumer;
  32 
  33 /**
  34  * A Red-Black tree based {@link NavigableMap} implementation.
  35  * The map is sorted according to the {@linkplain Comparable natural
  36  * ordering} of its keys, or by a {@link Comparator} provided at map
  37  * creation time, depending on which constructor is used.
  38  *
  39  * <p>This implementation provides guaranteed log(n) time cost for the
  40  * {@code containsKey}, {@code get}, {@code put} and {@code remove}
  41  * operations.  Algorithms are adaptations of those in Cormen, Leiserson, and
  42  * Rivest's <em>Introduction to Algorithms</em>.
  43  *
  44  * <p>Note that the ordering maintained by a tree map, like any sorted map, and
  45  * whether or not an explicit comparator is provided, must be <em>consistent
  46  * with {@code equals}</em> if this sorted map is to correctly implement the
  47  * {@code Map} interface.  (See {@code Comparable} or {@code Comparator} for a
  48  * precise definition of <em>consistent with equals</em>.)  This is so because
  49  * the {@code Map} interface is defined in terms of the {@code equals}
  50  * operation, but a sorted map performs all key comparisons using its {@code
  51  * compareTo} (or {@code compare}) method, so two keys that are deemed equal by
  52  * this method are, from the standpoint of the sorted map, equal.  The behavior
  53  * of a sorted map <em>is</em> well-defined even if its ordering is
  54  * inconsistent with {@code equals}; it just fails to obey the general contract
  55  * of the {@code Map} interface.
  56  *
  57  * <p><strong>Note that this implementation is not synchronized.</strong>
  58  * If multiple threads access a map concurrently, and at least one of the
  59  * threads modifies the map structurally, it <em>must</em> be synchronized
  60  * externally.  (A structural modification is any operation that adds or
  61  * deletes one or more mappings; merely changing the value associated
  62  * with an existing key is not a structural modification.)  This is
  63  * typically accomplished by synchronizing on some object that naturally
  64  * encapsulates the map.
  65  * If no such object exists, the map should be "wrapped" using the
  66  * {@link Collections#synchronizedSortedMap Collections.synchronizedSortedMap}
  67  * method.  This is best done at creation time, to prevent accidental
  68  * unsynchronized access to the map: <pre>
  69  *   SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));</pre>
  70  *
  71  * <p>The iterators returned by the {@code iterator} method of the collections
  72  * returned by all of this class's "collection view methods" are
  73  * <em>fail-fast</em>: if the map is structurally modified at any time after
  74  * the iterator is created, in any way except through the iterator's own
  75  * {@code remove} method, the iterator will throw a {@link
  76  * ConcurrentModificationException}.  Thus, in the face of concurrent
  77  * modification, the iterator fails quickly and cleanly, rather than risking
  78  * arbitrary, non-deterministic behavior at an undetermined time in the future.
  79  *
  80  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  81  * as it is, generally speaking, impossible to make any hard guarantees in the
  82  * presence of unsynchronized concurrent modification.  Fail-fast iterators
  83  * throw {@code ConcurrentModificationException} on a best-effort basis.
  84  * Therefore, it would be wrong to write a program that depended on this
  85  * exception for its correctness:   <em>the fail-fast behavior of iterators
  86  * should be used only to detect bugs.</em>
  87  *
  88  * <p>All {@code Map.Entry} pairs returned by methods in this class
  89  * and its views represent snapshots of mappings at the time they were
  90  * produced. They do <strong>not</strong> support the {@code Entry.setValue}
  91  * method. (Note however that it is possible to change mappings in the
  92  * associated map using {@code put}.)
  93  *
  94  * <p>This class is a member of the
  95  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  96  * Java Collections Framework</a>.
  97  *
  98  * @param <K> the type of keys maintained by this map
  99  * @param <V> the type of mapped values
 100  *
 101  * @author  Josh Bloch and Doug Lea
 102  * @see Map
 103  * @see HashMap
 104  * @see Hashtable
 105  * @see Comparable
 106  * @see Comparator
 107  * @see Collection
 108  * @since 1.2
 109  */
 110 
 111 public class TreeMap<K,V>
 112     extends AbstractMap<K,V>
 113     implements NavigableMap<K,V>, Cloneable, java.io.Serializable
 114 {
 115     /**
 116      * The comparator used to maintain order in this tree map, or
 117      * null if it uses the natural ordering of its keys.
 118      *
 119      * @serial
 120      */
 121     private final Comparator<? super K> comparator;
 122 
 123     private transient Entry<K,V> root;
 124 
 125     /**
 126      * The number of entries in the tree
 127      */
 128     private transient int size = 0;
 129 
 130     /**
 131      * The number of structural modifications to the tree.
 132      */
 133     private transient int modCount = 0;
 134 
 135     /**
 136      * Constructs a new, empty tree map, using the natural ordering of its
 137      * keys.  All keys inserted into the map must implement the {@link
 138      * Comparable} interface.  Furthermore, all such keys must be
 139      * <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
 140      * a {@code ClassCastException} for any keys {@code k1} and
 141      * {@code k2} in the map.  If the user attempts to put a key into the
 142      * map that violates this constraint (for example, the user attempts to
 143      * put a string key into a map whose keys are integers), the
 144      * {@code put(Object key, Object value)} call will throw a
 145      * {@code ClassCastException}.
 146      */
 147     public TreeMap() {
 148         comparator = null;
 149     }
 150 
 151     /**
 152      * Constructs a new, empty tree map, ordered according to the given
 153      * comparator.  All keys inserted into the map must be <em>mutually
 154      * comparable</em> by the given comparator: {@code comparator.compare(k1,
 155      * k2)} must not throw a {@code ClassCastException} for any keys
 156      * {@code k1} and {@code k2} in the map.  If the user attempts to put
 157      * a key into the map that violates this constraint, the {@code put(Object
 158      * key, Object value)} call will throw a
 159      * {@code ClassCastException}.
 160      *
 161      * @param comparator the comparator that will be used to order this map.
 162      *        If {@code null}, the {@linkplain Comparable natural
 163      *        ordering} of the keys will be used.
 164      */
 165     public TreeMap(Comparator<? super K> comparator) {
 166         this.comparator = comparator;
 167     }
 168 
 169     /**
 170      * Constructs a new tree map containing the same mappings as the given
 171      * map, ordered according to the <em>natural ordering</em> of its keys.
 172      * All keys inserted into the new map must implement the {@link
 173      * Comparable} interface.  Furthermore, all such keys must be
 174      * <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
 175      * a {@code ClassCastException} for any keys {@code k1} and
 176      * {@code k2} in the map.  This method runs in n*log(n) time.
 177      *
 178      * @param  m the map whose mappings are to be placed in this map
 179      * @throws ClassCastException if the keys in m are not {@link Comparable},
 180      *         or are not mutually comparable
 181      * @throws NullPointerException if the specified map is null
 182      */
 183     public TreeMap(Map<? extends K, ? extends V> m) {
 184         comparator = null;
 185         putAll(m);
 186     }
 187 
 188     /**
 189      * Constructs a new tree map containing the same mappings and
 190      * using the same ordering as the specified sorted map.  This
 191      * method runs in linear time.
 192      *
 193      * @param  m the sorted map whose mappings are to be placed in this map,
 194      *         and whose comparator is to be used to sort this map
 195      * @throws NullPointerException if the specified map is null
 196      */
 197     public TreeMap(SortedMap<K, ? extends V> m) {
 198         comparator = m.comparator();
 199         try {
 200             buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
 201         } catch (java.io.IOException | ClassNotFoundException cannotHappen) {
 202         }
 203     }
 204 
 205 
 206     // Query Operations
 207 
 208     /**
 209      * Returns the number of key-value mappings in this map.
 210      *
 211      * @return the number of key-value mappings in this map
 212      */
 213     public int size() {
 214         return size;
 215     }
 216 
 217     /**
 218      * Returns {@code true} if this map contains a mapping for the specified
 219      * key.
 220      *
 221      * @param key key whose presence in this map is to be tested
 222      * @return {@code true} if this map contains a mapping for the
 223      *         specified key
 224      * @throws ClassCastException if the specified key cannot be compared
 225      *         with the keys currently in the map
 226      * @throws NullPointerException if the specified key is null
 227      *         and this map uses natural ordering, or its comparator
 228      *         does not permit null keys
 229      */
 230     public boolean containsKey(Object key) {
 231         return getEntry(key) != null;
 232     }
 233 
 234     /**
 235      * Returns {@code true} if this map maps one or more keys to the
 236      * specified value.  More formally, returns {@code true} if and only if
 237      * this map contains at least one mapping to a value {@code v} such
 238      * that {@code (value==null ? v==null : value.equals(v))}.  This
 239      * operation will probably require time linear in the map size for
 240      * most implementations.
 241      *
 242      * @param value value whose presence in this map is to be tested
 243      * @return {@code true} if a mapping to {@code value} exists;
 244      *         {@code false} otherwise
 245      * @since 1.2
 246      */
 247     public boolean containsValue(Object value) {
 248         for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
 249             if (valEquals(value, e.value))
 250                 return true;
 251         return false;
 252     }
 253 
 254     /**
 255      * Returns the value to which the specified key is mapped,
 256      * or {@code null} if this map contains no mapping for the key.
 257      *
 258      * <p>More formally, if this map contains a mapping from a key
 259      * {@code k} to a value {@code v} such that {@code key} compares
 260      * equal to {@code k} according to the map's ordering, then this
 261      * method returns {@code v}; otherwise it returns {@code null}.
 262      * (There can be at most one such mapping.)
 263      *
 264      * <p>A return value of {@code null} does not <em>necessarily</em>
 265      * indicate that the map contains no mapping for the key; it's also
 266      * possible that the map explicitly maps the key to {@code null}.
 267      * The {@link #containsKey containsKey} operation may be used to
 268      * distinguish these two cases.
 269      *
 270      * @throws ClassCastException if the specified key cannot be compared
 271      *         with the keys currently in the map
 272      * @throws NullPointerException if the specified key is null
 273      *         and this map uses natural ordering, or its comparator
 274      *         does not permit null keys
 275      */
 276     public V get(Object key) {
 277         Entry<K,V> p = getEntry(key);
 278         return (p==null ? null : p.value);
 279     }
 280 
 281     public Comparator<? super K> comparator() {
 282         return comparator;
 283     }
 284 
 285     /**
 286      * @throws NoSuchElementException {@inheritDoc}
 287      */
 288     public K firstKey() {
 289         return key(getFirstEntry());
 290     }
 291 
 292     /**
 293      * @throws NoSuchElementException {@inheritDoc}
 294      */
 295     public K lastKey() {
 296         return key(getLastEntry());
 297     }
 298 
 299     /**
 300      * Copies all of the mappings from the specified map to this map.
 301      * These mappings replace any mappings that this map had for any
 302      * of the keys currently in the specified map.
 303      *
 304      * @param  map mappings to be stored in this map
 305      * @throws ClassCastException if the class of a key or value in
 306      *         the specified map prevents it from being stored in this map
 307      * @throws NullPointerException if the specified map is null or
 308      *         the specified map contains a null key and this map does not
 309      *         permit null keys
 310      */
 311     public void putAll(Map<? extends K, ? extends V> map) {
 312         int mapSize = map.size();
 313         if (size==0 && mapSize!=0 && map instanceof SortedMap) {
 314             Comparator<?> c = ((SortedMap<?,?>)map).comparator();
 315             if (c == comparator || (c != null && c.equals(comparator))) {
 316                 ++modCount;
 317                 try {
 318                     buildFromSorted(mapSize, map.entrySet().iterator(),
 319                                     null, null);
 320                 } catch (java.io.IOException | ClassNotFoundException cannotHappen) {
 321                 }
 322                 return;
 323             }
 324         }
 325         super.putAll(map);
 326     }
 327 
 328     /**
 329      * Returns this map's entry for the given key, or {@code null} if the map
 330      * does not contain an entry for the key.
 331      *
 332      * @return this map's entry for the given key, or {@code null} if the map
 333      *         does not contain an entry for the key
 334      * @throws ClassCastException if the specified key cannot be compared
 335      *         with the keys currently in the map
 336      * @throws NullPointerException if the specified key is null
 337      *         and this map uses natural ordering, or its comparator
 338      *         does not permit null keys
 339      */
 340     final Entry<K,V> getEntry(Object key) {
 341         // Offload comparator-based version for sake of performance
 342         if (comparator != null)
 343             return getEntryUsingComparator(key);
 344         if (key == null)
 345             throw new NullPointerException();
 346         @SuppressWarnings("unchecked")
 347             Comparable<? super K> k = (Comparable<? super K>) key;
 348         Entry<K,V> p = root;
 349         while (p != null) {
 350             int cmp = k.compareTo(p.key);
 351             if (cmp < 0)
 352                 p = p.left;
 353             else if (cmp > 0)
 354                 p = p.right;
 355             else
 356                 return p;
 357         }
 358         return null;
 359     }
 360 
 361     /**
 362      * Version of getEntry using comparator. Split off from getEntry
 363      * for performance. (This is not worth doing for most methods,
 364      * that are less dependent on comparator performance, but is
 365      * worthwhile here.)
 366      */
 367     final Entry<K,V> getEntryUsingComparator(Object key) {
 368         @SuppressWarnings("unchecked")
 369             K k = (K) key;
 370         Comparator<? super K> cpr = comparator;
 371         if (cpr != null) {
 372             Entry<K,V> p = root;
 373             while (p != null) {
 374                 int cmp = cpr.compare(k, p.key);
 375                 if (cmp < 0)
 376                     p = p.left;
 377                 else if (cmp > 0)
 378                     p = p.right;
 379                 else
 380                     return p;
 381             }
 382         }
 383         return null;
 384     }
 385 
 386     /**
 387      * Gets the entry corresponding to the specified key; if no such entry
 388      * exists, returns the entry for the least key greater than the specified
 389      * key; if no such entry exists (i.e., the greatest key in the Tree is less
 390      * than the specified key), returns {@code null}.
 391      */
 392     final Entry<K,V> getCeilingEntry(K key) {
 393         Entry<K,V> p = root;
 394         while (p != null) {
 395             int cmp = compare(key, p.key);
 396             if (cmp < 0) {
 397                 if (p.left != null)
 398                     p = p.left;
 399                 else
 400                     return p;
 401             } else if (cmp > 0) {
 402                 if (p.right != null) {
 403                     p = p.right;
 404                 } else {
 405                     Entry<K,V> parent = p.parent;
 406                     Entry<K,V> ch = p;
 407                     while (parent != null && ch == parent.right) {
 408                         ch = parent;
 409                         parent = parent.parent;
 410                     }
 411                     return parent;
 412                 }
 413             } else
 414                 return p;
 415         }
 416         return null;
 417     }
 418 
 419     /**
 420      * Gets the entry corresponding to the specified key; if no such entry
 421      * exists, returns the entry for the greatest key less than the specified
 422      * key; if no such entry exists, returns {@code null}.
 423      */
 424     final Entry<K,V> getFloorEntry(K key) {
 425         Entry<K,V> p = root;
 426         while (p != null) {
 427             int cmp = compare(key, p.key);
 428             if (cmp > 0) {
 429                 if (p.right != null)
 430                     p = p.right;
 431                 else
 432                     return p;
 433             } else if (cmp < 0) {
 434                 if (p.left != null) {
 435                     p = p.left;
 436                 } else {
 437                     Entry<K,V> parent = p.parent;
 438                     Entry<K,V> ch = p;
 439                     while (parent != null && ch == parent.left) {
 440                         ch = parent;
 441                         parent = parent.parent;
 442                     }
 443                     return parent;
 444                 }
 445             } else
 446                 return p;
 447 
 448         }
 449         return null;
 450     }
 451 
 452     /**
 453      * Gets the entry for the least key greater than the specified
 454      * key; if no such entry exists, returns the entry for the least
 455      * key greater than the specified key; if no such entry exists
 456      * returns {@code null}.
 457      */
 458     final Entry<K,V> getHigherEntry(K key) {
 459         Entry<K,V> p = root;
 460         while (p != null) {
 461             int cmp = compare(key, p.key);
 462             if (cmp < 0) {
 463                 if (p.left != null)
 464                     p = p.left;
 465                 else
 466                     return p;
 467             } else {
 468                 if (p.right != null) {
 469                     p = p.right;
 470                 } else {
 471                     Entry<K,V> parent = p.parent;
 472                     Entry<K,V> ch = p;
 473                     while (parent != null && ch == parent.right) {
 474                         ch = parent;
 475                         parent = parent.parent;
 476                     }
 477                     return parent;
 478                 }
 479             }
 480         }
 481         return null;
 482     }
 483 
 484     /**
 485      * Returns the entry for the greatest key less than the specified key; if
 486      * no such entry exists (i.e., the least key in the Tree is greater than
 487      * the specified key), returns {@code null}.
 488      */
 489     final Entry<K,V> getLowerEntry(K key) {
 490         Entry<K,V> p = root;
 491         while (p != null) {
 492             int cmp = compare(key, p.key);
 493             if (cmp > 0) {
 494                 if (p.right != null)
 495                     p = p.right;
 496                 else
 497                     return p;
 498             } else {
 499                 if (p.left != null) {
 500                     p = p.left;
 501                 } else {
 502                     Entry<K,V> parent = p.parent;
 503                     Entry<K,V> ch = p;
 504                     while (parent != null && ch == parent.left) {
 505                         ch = parent;
 506                         parent = parent.parent;
 507                     }
 508                     return parent;
 509                 }
 510             }
 511         }
 512         return null;
 513     }
 514 
 515     /**
 516      * Associates the specified value with the specified key in this map.
 517      * If the map previously contained a mapping for the key, the old
 518      * value is replaced.
 519      *
 520      * @param key key with which the specified value is to be associated
 521      * @param value value to be associated with the specified key
 522      *
 523      * @return the previous value associated with {@code key}, or
 524      *         {@code null} if there was no mapping for {@code key}.
 525      *         (A {@code null} return can also indicate that the map
 526      *         previously associated {@code null} with {@code key}.)
 527      * @throws ClassCastException if the specified key cannot be compared
 528      *         with the keys currently in the map
 529      * @throws NullPointerException if the specified key is null
 530      *         and this map uses natural ordering, or its comparator
 531      *         does not permit null keys
 532      */
 533     public V put(K key, V value) {
 534         Entry<K,V> t = root;
 535         if (t == null) {
 536             compare(key, key); // type (and possibly null) check
 537 
 538             root = new Entry<>(key, value, null);
 539             size = 1;
 540             modCount++;
 541             return null;
 542         }
 543         int cmp;
 544         Entry<K,V> parent;
 545         // split comparator and comparable paths
 546         Comparator<? super K> cpr = comparator;
 547         if (cpr != null) {
 548             do {
 549                 parent = t;
 550                 cmp = cpr.compare(key, t.key);
 551                 if (cmp < 0)
 552                     t = t.left;
 553                 else if (cmp > 0)
 554                     t = t.right;
 555                 else
 556                     return t.setValue(value);
 557             } while (t != null);
 558         }
 559         else {
 560             if (key == null)
 561                 throw new NullPointerException();
 562             @SuppressWarnings("unchecked")
 563                 Comparable<? super K> k = (Comparable<? super K>) key;
 564             do {
 565                 parent = t;
 566                 cmp = k.compareTo(t.key);
 567                 if (cmp < 0)
 568                     t = t.left;
 569                 else if (cmp > 0)
 570                     t = t.right;
 571                 else
 572                     return t.setValue(value);
 573             } while (t != null);
 574         }
 575         Entry<K,V> e = new Entry<>(key, value, parent);
 576         if (cmp < 0)
 577             parent.left = e;
 578         else
 579             parent.right = e;
 580         fixAfterInsertion(e);
 581         size++;
 582         modCount++;
 583         return null;
 584     }
 585 
 586     /**
 587      * Removes the mapping for this key from this TreeMap if present.
 588      *
 589      * @param  key key for which mapping should be removed
 590      * @return the previous value associated with {@code key}, or
 591      *         {@code null} if there was no mapping for {@code key}.
 592      *         (A {@code null} return can also indicate that the map
 593      *         previously associated {@code null} with {@code key}.)
 594      * @throws ClassCastException if the specified key cannot be compared
 595      *         with the keys currently in the map
 596      * @throws NullPointerException if the specified key is null
 597      *         and this map uses natural ordering, or its comparator
 598      *         does not permit null keys
 599      */
 600     public V remove(Object key) {
 601         Entry<K,V> p = getEntry(key);
 602         if (p == null)
 603             return null;
 604 
 605         V oldValue = p.value;
 606         deleteEntry(p);
 607         return oldValue;
 608     }
 609 
 610     /**
 611      * Removes all of the mappings from this map.
 612      * The map will be empty after this call returns.
 613      */
 614     public void clear() {
 615         modCount++;
 616         size = 0;
 617         root = null;
 618     }
 619 
 620     /**
 621      * Returns a shallow copy of this {@code TreeMap} instance. (The keys and
 622      * values themselves are not cloned.)
 623      *
 624      * @return a shallow copy of this map
 625      */
 626     public Object clone() {
 627         TreeMap<?,?> clone;
 628         try {
 629             clone = (TreeMap<?,?>) super.clone();
 630         } catch (CloneNotSupportedException e) {
 631             throw new InternalError(e);
 632         }
 633 
 634         // Put clone into "virgin" state (except for comparator)
 635         clone.root = null;
 636         clone.size = 0;
 637         clone.modCount = 0;
 638         clone.entrySet = null;
 639         clone.navigableKeySet = null;
 640         clone.descendingMap = null;
 641 
 642         // Initialize clone with our mappings
 643         try {
 644             clone.buildFromSorted(size, entrySet().iterator(), null, null);
 645         } catch (java.io.IOException | ClassNotFoundException cannotHappen) {
 646         }
 647 
 648         return clone;
 649     }
 650 
 651     // NavigableMap API methods
 652 
 653     /**
 654      * @since 1.6
 655      */
 656     public Map.Entry<K,V> firstEntry() {
 657         return exportEntry(getFirstEntry());
 658     }
 659 
 660     /**
 661      * @since 1.6
 662      */
 663     public Map.Entry<K,V> lastEntry() {
 664         return exportEntry(getLastEntry());
 665     }
 666 
 667     /**
 668      * @since 1.6
 669      */
 670     public Map.Entry<K,V> pollFirstEntry() {
 671         Entry<K,V> p = getFirstEntry();
 672         Map.Entry<K,V> result = exportEntry(p);
 673         if (p != null)
 674             deleteEntry(p);
 675         return result;
 676     }
 677 
 678     /**
 679      * @since 1.6
 680      */
 681     public Map.Entry<K,V> pollLastEntry() {
 682         Entry<K,V> p = getLastEntry();
 683         Map.Entry<K,V> result = exportEntry(p);
 684         if (p != null)
 685             deleteEntry(p);
 686         return result;
 687     }
 688 
 689     /**
 690      * @throws ClassCastException {@inheritDoc}
 691      * @throws NullPointerException if the specified key is null
 692      *         and this map uses natural ordering, or its comparator
 693      *         does not permit null keys
 694      * @since 1.6
 695      */
 696     public Map.Entry<K,V> lowerEntry(K key) {
 697         return exportEntry(getLowerEntry(key));
 698     }
 699 
 700     /**
 701      * @throws ClassCastException {@inheritDoc}
 702      * @throws NullPointerException if the specified key is null
 703      *         and this map uses natural ordering, or its comparator
 704      *         does not permit null keys
 705      * @since 1.6
 706      */
 707     public K lowerKey(K key) {
 708         return keyOrNull(getLowerEntry(key));
 709     }
 710 
 711     /**
 712      * @throws ClassCastException {@inheritDoc}
 713      * @throws NullPointerException if the specified key is null
 714      *         and this map uses natural ordering, or its comparator
 715      *         does not permit null keys
 716      * @since 1.6
 717      */
 718     public Map.Entry<K,V> floorEntry(K key) {
 719         return exportEntry(getFloorEntry(key));
 720     }
 721 
 722     /**
 723      * @throws ClassCastException {@inheritDoc}
 724      * @throws NullPointerException if the specified key is null
 725      *         and this map uses natural ordering, or its comparator
 726      *         does not permit null keys
 727      * @since 1.6
 728      */
 729     public K floorKey(K key) {
 730         return keyOrNull(getFloorEntry(key));
 731     }
 732 
 733     /**
 734      * @throws ClassCastException {@inheritDoc}
 735      * @throws NullPointerException if the specified key is null
 736      *         and this map uses natural ordering, or its comparator
 737      *         does not permit null keys
 738      * @since 1.6
 739      */
 740     public Map.Entry<K,V> ceilingEntry(K key) {
 741         return exportEntry(getCeilingEntry(key));
 742     }
 743 
 744     /**
 745      * @throws ClassCastException {@inheritDoc}
 746      * @throws NullPointerException if the specified key is null
 747      *         and this map uses natural ordering, or its comparator
 748      *         does not permit null keys
 749      * @since 1.6
 750      */
 751     public K ceilingKey(K key) {
 752         return keyOrNull(getCeilingEntry(key));
 753     }
 754 
 755     /**
 756      * @throws ClassCastException {@inheritDoc}
 757      * @throws NullPointerException if the specified key is null
 758      *         and this map uses natural ordering, or its comparator
 759      *         does not permit null keys
 760      * @since 1.6
 761      */
 762     public Map.Entry<K,V> higherEntry(K key) {
 763         return exportEntry(getHigherEntry(key));
 764     }
 765 
 766     /**
 767      * @throws ClassCastException {@inheritDoc}
 768      * @throws NullPointerException if the specified key is null
 769      *         and this map uses natural ordering, or its comparator
 770      *         does not permit null keys
 771      * @since 1.6
 772      */
 773     public K higherKey(K key) {
 774         return keyOrNull(getHigherEntry(key));
 775     }
 776 
 777     // Views
 778 
 779     /**
 780      * Fields initialized to contain an instance of the entry set view
 781      * the first time this view is requested.  Views are stateless, so
 782      * there's no reason to create more than one.
 783      */
 784     private transient EntrySet entrySet;
 785     private transient KeySet<K> navigableKeySet;
 786     private transient NavigableMap<K,V> descendingMap;
 787 
 788     /**
 789      * Returns a {@link Set} view of the keys contained in this map.
 790      *
 791      * <p>The set's iterator returns the keys in ascending order.
 792      * The set's spliterator is
 793      * <em><a href="Spliterator.html#binding">late-binding</a></em>,
 794      * <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED}
 795      * and {@link Spliterator#ORDERED} with an encounter order that is ascending
 796      * key order.  The spliterator's comparator (see
 797      * {@link java.util.Spliterator#getComparator()}) is {@code null} if
 798      * the tree map's comparator (see {@link #comparator()}) is {@code null}.
 799      * Otherwise, the spliterator's comparator is the same as or imposes the
 800      * same total ordering as the tree map's comparator.
 801      *
 802      * <p>The set is backed by the map, so changes to the map are
 803      * reflected in the set, and vice-versa.  If the map is modified
 804      * while an iteration over the set is in progress (except through
 805      * the iterator's own {@code remove} operation), the results of
 806      * the iteration are undefined.  The set supports element removal,
 807      * which removes the corresponding mapping from the map, via the
 808      * {@code Iterator.remove}, {@code Set.remove},
 809      * {@code removeAll}, {@code retainAll}, and {@code clear}
 810      * operations.  It does not support the {@code add} or {@code addAll}
 811      * operations.
 812      */
 813     public Set<K> keySet() {
 814         return navigableKeySet();
 815     }
 816 
 817     /**
 818      * @since 1.6
 819      */
 820     public NavigableSet<K> navigableKeySet() {
 821         KeySet<K> nks = navigableKeySet;
 822         return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
 823     }
 824 
 825     /**
 826      * @since 1.6
 827      */
 828     public NavigableSet<K> descendingKeySet() {
 829         return descendingMap().navigableKeySet();
 830     }
 831 
 832     /**
 833      * Returns a {@link Collection} view of the values contained in this map.
 834      *
 835      * <p>The collection's iterator returns the values in ascending order
 836      * of the corresponding keys. The collection's spliterator is
 837      * <em><a href="Spliterator.html#binding">late-binding</a></em>,
 838      * <em>fail-fast</em>, and additionally reports {@link Spliterator#ORDERED}
 839      * with an encounter order that is ascending order of the corresponding
 840      * keys.
 841      *
 842      * <p>The collection is backed by the map, so changes to the map are
 843      * reflected in the collection, and vice-versa.  If the map is
 844      * modified while an iteration over the collection is in progress
 845      * (except through the iterator's own {@code remove} operation),
 846      * the results of the iteration are undefined.  The collection
 847      * supports element removal, which removes the corresponding
 848      * mapping from the map, via the {@code Iterator.remove},
 849      * {@code Collection.remove}, {@code removeAll},
 850      * {@code retainAll} and {@code clear} operations.  It does not
 851      * support the {@code add} or {@code addAll} operations.
 852      */
 853     public Collection<V> values() {
 854         Collection<V> vs = values;
 855         if (vs == null) {
 856             vs = new Values();
 857             values = vs;
 858         }
 859         return vs;
 860     }
 861 
 862     /**
 863      * Returns a {@link Set} view of the mappings contained in this map.
 864      *
 865      * <p>The set's iterator returns the entries in ascending key order. The
 866      * set's spliterator is
 867      * <em><a href="Spliterator.html#binding">late-binding</a></em>,
 868      * <em>fail-fast</em>, and additionally reports {@link Spliterator#SORTED} and
 869      * {@link Spliterator#ORDERED} with an encounter order that is ascending key
 870      * order.
 871      *
 872      * <p>The set is backed by the map, so changes to the map are
 873      * reflected in the set, and vice-versa.  If the map is modified
 874      * while an iteration over the set is in progress (except through
 875      * the iterator's own {@code remove} operation, or through the
 876      * {@code setValue} operation on a map entry returned by the
 877      * iterator) the results of the iteration are undefined.  The set
 878      * supports element removal, which removes the corresponding
 879      * mapping from the map, via the {@code Iterator.remove},
 880      * {@code Set.remove}, {@code removeAll}, {@code retainAll} and
 881      * {@code clear} operations.  It does not support the
 882      * {@code add} or {@code addAll} operations.
 883      */
 884     public Set<Map.Entry<K,V>> entrySet() {
 885         EntrySet es = entrySet;
 886         return (es != null) ? es : (entrySet = new EntrySet());
 887     }
 888 
 889     /**
 890      * @since 1.6
 891      */
 892     public NavigableMap<K, V> descendingMap() {
 893         NavigableMap<K, V> km = descendingMap;
 894         return (km != null) ? km :
 895             (descendingMap = new DescendingSubMap<>(this,
 896                                                     true, null, true,
 897                                                     true, null, true));
 898     }
 899 
 900     /**
 901      * @throws ClassCastException       {@inheritDoc}
 902      * @throws NullPointerException if {@code fromKey} or {@code toKey} is
 903      *         null and this map uses natural ordering, or its comparator
 904      *         does not permit null keys
 905      * @throws IllegalArgumentException {@inheritDoc}
 906      * @since 1.6
 907      */
 908     public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
 909                                     K toKey,   boolean toInclusive) {
 910         return new AscendingSubMap<>(this,
 911                                      false, fromKey, fromInclusive,
 912                                      false, toKey,   toInclusive);
 913     }
 914 
 915     /**
 916      * @throws ClassCastException       {@inheritDoc}
 917      * @throws NullPointerException if {@code toKey} is null
 918      *         and this map uses natural ordering, or its comparator
 919      *         does not permit null keys
 920      * @throws IllegalArgumentException {@inheritDoc}
 921      * @since 1.6
 922      */
 923     public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
 924         return new AscendingSubMap<>(this,
 925                                      true,  null,  true,
 926                                      false, toKey, inclusive);
 927     }
 928 
 929     /**
 930      * @throws ClassCastException       {@inheritDoc}
 931      * @throws NullPointerException if {@code fromKey} is null
 932      *         and this map uses natural ordering, or its comparator
 933      *         does not permit null keys
 934      * @throws IllegalArgumentException {@inheritDoc}
 935      * @since 1.6
 936      */
 937     public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
 938         return new AscendingSubMap<>(this,
 939                                      false, fromKey, inclusive,
 940                                      true,  null,    true);
 941     }
 942 
 943     /**
 944      * @throws ClassCastException       {@inheritDoc}
 945      * @throws NullPointerException if {@code fromKey} or {@code toKey} is
 946      *         null and this map uses natural ordering, or its comparator
 947      *         does not permit null keys
 948      * @throws IllegalArgumentException {@inheritDoc}
 949      */
 950     public SortedMap<K,V> subMap(K fromKey, K toKey) {
 951         return subMap(fromKey, true, toKey, false);
 952     }
 953 
 954     /**
 955      * @throws ClassCastException       {@inheritDoc}
 956      * @throws NullPointerException if {@code toKey} is null
 957      *         and this map uses natural ordering, or its comparator
 958      *         does not permit null keys
 959      * @throws IllegalArgumentException {@inheritDoc}
 960      */
 961     public SortedMap<K,V> headMap(K toKey) {
 962         return headMap(toKey, false);
 963     }
 964 
 965     /**
 966      * @throws ClassCastException       {@inheritDoc}
 967      * @throws NullPointerException if {@code fromKey} is null
 968      *         and this map uses natural ordering, or its comparator
 969      *         does not permit null keys
 970      * @throws IllegalArgumentException {@inheritDoc}
 971      */
 972     public SortedMap<K,V> tailMap(K fromKey) {
 973         return tailMap(fromKey, true);
 974     }
 975 
 976     @Override
 977     public boolean replace(K key, V oldValue, V newValue) {
 978         Entry<K,V> p = getEntry(key);
 979         if (p!=null && Objects.equals(oldValue, p.value)) {
 980             p.value = newValue;
 981             return true;
 982         }
 983         return false;
 984     }
 985 
 986     @Override
 987     public V replace(K key, V value) {
 988         Entry<K,V> p = getEntry(key);
 989         if (p!=null) {
 990             V oldValue = p.value;
 991             p.value = value;
 992             return oldValue;
 993         }
 994         return null;
 995     }
 996 
 997     @Override
 998     public void forEach(BiConsumer<? super K, ? super V> action) {
 999         Objects.requireNonNull(action);
1000         int expectedModCount = modCount;
1001         for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
1002             action.accept(e.key, e.value);
1003 
1004             if (expectedModCount != modCount) {
1005                 throw new ConcurrentModificationException();
1006             }
1007         }
1008     }
1009 
1010     @Override
1011     public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1012         Objects.requireNonNull(function);
1013         int expectedModCount = modCount;
1014 
1015         for (Entry<K, V> e = getFirstEntry(); e != null; e = successor(e)) {
1016             e.value = function.apply(e.key, e.value);
1017 
1018             if (expectedModCount != modCount) {
1019                 throw new ConcurrentModificationException();
1020             }
1021         }
1022     }
1023 
1024     // View class support
1025 
1026     class Values extends AbstractCollection<V> {
1027         public Iterator<V> iterator() {
1028             return new ValueIterator(getFirstEntry());
1029         }
1030 
1031         public int size() {
1032             return TreeMap.this.size();
1033         }
1034 
1035         public boolean contains(Object o) {
1036             return TreeMap.this.containsValue(o);
1037         }
1038 
1039         public boolean remove(Object o) {
1040             for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
1041                 if (valEquals(e.getValue(), o)) {
1042                     deleteEntry(e);
1043                     return true;
1044                 }
1045             }
1046             return false;
1047         }
1048 
1049         public void clear() {
1050             TreeMap.this.clear();
1051         }
1052 
1053         public Spliterator<V> spliterator() {
1054             return new ValueSpliterator<>(TreeMap.this, null, null, 0, -1, 0);
1055         }
1056     }
1057 
1058     class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1059         public Iterator<Map.Entry<K,V>> iterator() {
1060             return new EntryIterator(getFirstEntry());
1061         }
1062 
1063         public boolean contains(Object o) {
1064             if (!(o instanceof Map.Entry))
1065                 return false;
1066             Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
1067             Object value = entry.getValue();
1068             Entry<K,V> p = getEntry(entry.getKey());
1069             return p != null && valEquals(p.getValue(), value);
1070         }
1071 
1072         public boolean remove(Object o) {
1073             if (!(o instanceof Map.Entry))
1074                 return false;
1075             Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
1076             Object value = entry.getValue();
1077             Entry<K,V> p = getEntry(entry.getKey());
1078             if (p != null && valEquals(p.getValue(), value)) {
1079                 deleteEntry(p);
1080                 return true;
1081             }
1082             return false;
1083         }
1084 
1085         public int size() {
1086             return TreeMap.this.size();
1087         }
1088 
1089         public void clear() {
1090             TreeMap.this.clear();
1091         }
1092 
1093         public Spliterator<Map.Entry<K,V>> spliterator() {
1094             return new EntrySpliterator<>(TreeMap.this, null, null, 0, -1, 0);
1095         }
1096     }
1097 
1098     /*
1099      * Unlike Values and EntrySet, the KeySet class is static,
1100      * delegating to a NavigableMap to allow use by SubMaps, which
1101      * outweighs the ugliness of needing type-tests for the following
1102      * Iterator methods that are defined appropriately in main versus
1103      * submap classes.
1104      */
1105 
1106     Iterator<K> keyIterator() {
1107         return new KeyIterator(getFirstEntry());
1108     }
1109 
1110     Iterator<K> descendingKeyIterator() {
1111         return new DescendingKeyIterator(getLastEntry());
1112     }
1113 
1114     static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
1115         private final NavigableMap<E, ?> m;
1116         KeySet(NavigableMap<E,?> map) { m = map; }
1117 
1118         public Iterator<E> iterator() {
1119             if (m instanceof TreeMap)
1120                 return ((TreeMap<E,?>)m).keyIterator();
1121             else
1122                 return ((TreeMap.NavigableSubMap<E,?>)m).keyIterator();
1123         }
1124 
1125         public Iterator<E> descendingIterator() {
1126             if (m instanceof TreeMap)
1127                 return ((TreeMap<E,?>)m).descendingKeyIterator();
1128             else
1129                 return ((TreeMap.NavigableSubMap<E,?>)m).descendingKeyIterator();
1130         }
1131 
1132         public int size() { return m.size(); }
1133         public boolean isEmpty() { return m.isEmpty(); }
1134         public boolean contains(Object o) { return m.containsKey(o); }
1135         public void clear() { m.clear(); }
1136         public E lower(E e) { return m.lowerKey(e); }
1137         public E floor(E e) { return m.floorKey(e); }
1138         public E ceiling(E e) { return m.ceilingKey(e); }
1139         public E higher(E e) { return m.higherKey(e); }
1140         public E first() { return m.firstKey(); }
1141         public E last() { return m.lastKey(); }
1142         public Comparator<? super E> comparator() { return m.comparator(); }
1143         public E pollFirst() {
1144             Map.Entry<E,?> e = m.pollFirstEntry();
1145             return (e == null) ? null : e.getKey();
1146         }
1147         public E pollLast() {
1148             Map.Entry<E,?> e = m.pollLastEntry();
1149             return (e == null) ? null : e.getKey();
1150         }
1151         public boolean remove(Object o) {
1152             int oldSize = size();
1153             m.remove(o);
1154             return size() != oldSize;
1155         }
1156         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
1157                                       E toElement,   boolean toInclusive) {
1158             return new KeySet<>(m.subMap(fromElement, fromInclusive,
1159                                           toElement,   toInclusive));
1160         }
1161         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1162             return new KeySet<>(m.headMap(toElement, inclusive));
1163         }
1164         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1165             return new KeySet<>(m.tailMap(fromElement, inclusive));
1166         }
1167         public SortedSet<E> subSet(E fromElement, E toElement) {
1168             return subSet(fromElement, true, toElement, false);
1169         }
1170         public SortedSet<E> headSet(E toElement) {
1171             return headSet(toElement, false);
1172         }
1173         public SortedSet<E> tailSet(E fromElement) {
1174             return tailSet(fromElement, true);
1175         }
1176         public NavigableSet<E> descendingSet() {
1177             return new KeySet<>(m.descendingMap());
1178         }
1179 
1180         public Spliterator<E> spliterator() {
1181             return keySpliteratorFor(m);
1182         }
1183     }
1184 
1185     /**
1186      * Base class for TreeMap Iterators
1187      */
1188     abstract class PrivateEntryIterator<T> implements Iterator<T> {
1189         Entry<K,V> next;
1190         Entry<K,V> lastReturned;
1191         int expectedModCount;
1192 
1193         PrivateEntryIterator(Entry<K,V> first) {
1194             expectedModCount = modCount;
1195             lastReturned = null;
1196             next = first;
1197         }
1198 
1199         public final boolean hasNext() {
1200             return next != null;
1201         }
1202 
1203         final Entry<K,V> nextEntry() {
1204             Entry<K,V> e = next;
1205             if (e == null)
1206                 throw new NoSuchElementException();
1207             if (modCount != expectedModCount)
1208                 throw new ConcurrentModificationException();
1209             next = successor(e);
1210             lastReturned = e;
1211             return e;
1212         }
1213 
1214         final Entry<K,V> prevEntry() {
1215             Entry<K,V> e = next;
1216             if (e == null)
1217                 throw new NoSuchElementException();
1218             if (modCount != expectedModCount)
1219                 throw new ConcurrentModificationException();
1220             next = predecessor(e);
1221             lastReturned = e;
1222             return e;
1223         }
1224 
1225         public void remove() {
1226             if (lastReturned == null)
1227                 throw new IllegalStateException();
1228             if (modCount != expectedModCount)
1229                 throw new ConcurrentModificationException();
1230             // deleted entries are replaced by their successors
1231             if (lastReturned.left != null && lastReturned.right != null)
1232                 next = lastReturned;
1233             deleteEntry(lastReturned);
1234             expectedModCount = modCount;
1235             lastReturned = null;
1236         }
1237     }
1238 
1239     final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1240         EntryIterator(Entry<K,V> first) {
1241             super(first);
1242         }
1243         public Map.Entry<K,V> next() {
1244             return nextEntry();
1245         }
1246     }
1247 
1248     final class ValueIterator extends PrivateEntryIterator<V> {
1249         ValueIterator(Entry<K,V> first) {
1250             super(first);
1251         }
1252         public V next() {
1253             return nextEntry().value;
1254         }
1255     }
1256 
1257     final class KeyIterator extends PrivateEntryIterator<K> {
1258         KeyIterator(Entry<K,V> first) {
1259             super(first);
1260         }
1261         public K next() {
1262             return nextEntry().key;
1263         }
1264     }
1265 
1266     final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1267         DescendingKeyIterator(Entry<K,V> first) {
1268             super(first);
1269         }
1270         public K next() {
1271             return prevEntry().key;
1272         }
1273         public void remove() {
1274             if (lastReturned == null)
1275                 throw new IllegalStateException();
1276             if (modCount != expectedModCount)
1277                 throw new ConcurrentModificationException();
1278             deleteEntry(lastReturned);
1279             lastReturned = null;
1280             expectedModCount = modCount;
1281         }
1282     }
1283 
1284     // Little utilities
1285 
1286     /**
1287      * Compares two keys using the correct comparison method for this TreeMap.
1288      */
1289     @SuppressWarnings("unchecked")
1290     final int compare(Object k1, Object k2) {
1291         return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1292             : comparator.compare((K)k1, (K)k2);
1293     }
1294 
1295     /**
1296      * Test two values for equality.  Differs from o1.equals(o2) only in
1297      * that it copes with {@code null} o1 properly.
1298      */
1299     static final boolean valEquals(Object o1, Object o2) {
1300         return (o1==null ? o2==null : o1.equals(o2));
1301     }
1302 
1303     /**
1304      * Return SimpleImmutableEntry for entry, or null if null
1305      */
1306     static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
1307         return (e == null) ? null :
1308             new AbstractMap.SimpleImmutableEntry<>(e);
1309     }
1310 
1311     /**
1312      * Return key for entry, or null if null
1313      */
1314     static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
1315         return (e == null) ? null : e.key;
1316     }
1317 
1318     /**
1319      * Returns the key corresponding to the specified Entry.
1320      * @throws NoSuchElementException if the Entry is null
1321      */
1322     static <K> K key(Entry<K,?> e) {
1323         if (e==null)
1324             throw new NoSuchElementException();
1325         return e.key;
1326     }
1327 
1328 
1329     // SubMaps
1330 
1331     /**
1332      * Dummy value serving as unmatchable fence key for unbounded
1333      * SubMapIterators
1334      */
1335     private static final Object UNBOUNDED = new Object();
1336 
1337     /**
1338      * @serial include
1339      */
1340     abstract static class NavigableSubMap<K,V> extends AbstractMap<K,V>
1341         implements NavigableMap<K,V>, java.io.Serializable {
1342         private static final long serialVersionUID = -2102997345730753016L;
1343         /**
1344          * The backing map.
1345          */
1346         final TreeMap<K,V> m;
1347 
1348         /**
1349          * Endpoints are represented as triples (fromStart, lo,
1350          * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is
1351          * true, then the low (absolute) bound is the start of the
1352          * backing map, and the other values are ignored. Otherwise,
1353          * if loInclusive is true, lo is the inclusive bound, else lo
1354          * is the exclusive bound. Similarly for the upper bound.
1355          */
1356         final K lo, hi;
1357         final boolean fromStart, toEnd;
1358         final boolean loInclusive, hiInclusive;
1359 
1360         NavigableSubMap(TreeMap<K,V> m,
1361                         boolean fromStart, K lo, boolean loInclusive,
1362                         boolean toEnd,     K hi, boolean hiInclusive) {
1363             if (!fromStart && !toEnd) {
1364                 if (m.compare(lo, hi) > 0)
1365                     throw new IllegalArgumentException("fromKey > toKey");
1366             } else {
1367                 if (!fromStart) // type check
1368                     m.compare(lo, lo);
1369                 if (!toEnd)
1370                     m.compare(hi, hi);
1371             }
1372 
1373             this.m = m;
1374             this.fromStart = fromStart;
1375             this.lo = lo;
1376             this.loInclusive = loInclusive;
1377             this.toEnd = toEnd;
1378             this.hi = hi;
1379             this.hiInclusive = hiInclusive;
1380         }
1381 
1382         // internal utilities
1383 
1384         final boolean tooLow(Object key) {
1385             if (!fromStart) {
1386                 int c = m.compare(key, lo);
1387                 if (c < 0 || (c == 0 && !loInclusive))
1388                     return true;
1389             }
1390             return false;
1391         }
1392 
1393         final boolean tooHigh(Object key) {
1394             if (!toEnd) {
1395                 int c = m.compare(key, hi);
1396                 if (c > 0 || (c == 0 && !hiInclusive))
1397                     return true;
1398             }
1399             return false;
1400         }
1401 
1402         final boolean inRange(Object key) {
1403             return !tooLow(key) && !tooHigh(key);
1404         }
1405 
1406         final boolean inClosedRange(Object key) {
1407             return (fromStart || m.compare(key, lo) >= 0)
1408                 && (toEnd || m.compare(hi, key) >= 0);
1409         }
1410 
1411         final boolean inRange(Object key, boolean inclusive) {
1412             return inclusive ? inRange(key) : inClosedRange(key);
1413         }
1414 
1415         /*
1416          * Absolute versions of relation operations.
1417          * Subclasses map to these using like-named "sub"
1418          * versions that invert senses for descending maps
1419          */
1420 
1421         final TreeMap.Entry<K,V> absLowest() {
1422             TreeMap.Entry<K,V> e =
1423                 (fromStart ?  m.getFirstEntry() :
1424                  (loInclusive ? m.getCeilingEntry(lo) :
1425                                 m.getHigherEntry(lo)));
1426             return (e == null || tooHigh(e.key)) ? null : e;
1427         }
1428 
1429         final TreeMap.Entry<K,V> absHighest() {
1430             TreeMap.Entry<K,V> e =
1431                 (toEnd ?  m.getLastEntry() :
1432                  (hiInclusive ?  m.getFloorEntry(hi) :
1433                                  m.getLowerEntry(hi)));
1434             return (e == null || tooLow(e.key)) ? null : e;
1435         }
1436 
1437         final TreeMap.Entry<K,V> absCeiling(K key) {
1438             if (tooLow(key))
1439                 return absLowest();
1440             TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
1441             return (e == null || tooHigh(e.key)) ? null : e;
1442         }
1443 
1444         final TreeMap.Entry<K,V> absHigher(K key) {
1445             if (tooLow(key))
1446                 return absLowest();
1447             TreeMap.Entry<K,V> e = m.getHigherEntry(key);
1448             return (e == null || tooHigh(e.key)) ? null : e;
1449         }
1450 
1451         final TreeMap.Entry<K,V> absFloor(K key) {
1452             if (tooHigh(key))
1453                 return absHighest();
1454             TreeMap.Entry<K,V> e = m.getFloorEntry(key);
1455             return (e == null || tooLow(e.key)) ? null : e;
1456         }
1457 
1458         final TreeMap.Entry<K,V> absLower(K key) {
1459             if (tooHigh(key))
1460                 return absHighest();
1461             TreeMap.Entry<K,V> e = m.getLowerEntry(key);
1462             return (e == null || tooLow(e.key)) ? null : e;
1463         }
1464 
1465         /** Returns the absolute high fence for ascending traversal */
1466         final TreeMap.Entry<K,V> absHighFence() {
1467             return (toEnd ? null : (hiInclusive ?
1468                                     m.getHigherEntry(hi) :
1469                                     m.getCeilingEntry(hi)));
1470         }
1471 
1472         /** Return the absolute low fence for descending traversal  */
1473         final TreeMap.Entry<K,V> absLowFence() {
1474             return (fromStart ? null : (loInclusive ?
1475                                         m.getLowerEntry(lo) :
1476                                         m.getFloorEntry(lo)));
1477         }
1478 
1479         // Abstract methods defined in ascending vs descending classes
1480         // These relay to the appropriate absolute versions
1481 
1482         abstract TreeMap.Entry<K,V> subLowest();
1483         abstract TreeMap.Entry<K,V> subHighest();
1484         abstract TreeMap.Entry<K,V> subCeiling(K key);
1485         abstract TreeMap.Entry<K,V> subHigher(K key);
1486         abstract TreeMap.Entry<K,V> subFloor(K key);
1487         abstract TreeMap.Entry<K,V> subLower(K key);
1488 
1489         /** Returns ascending iterator from the perspective of this submap */
1490         abstract Iterator<K> keyIterator();
1491 
1492         abstract Spliterator<K> keySpliterator();
1493 
1494         /** Returns descending iterator from the perspective of this submap */
1495         abstract Iterator<K> descendingKeyIterator();
1496 
1497         // public methods
1498 
1499         public boolean isEmpty() {
1500             return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1501         }
1502 
1503         public int size() {
1504             return (fromStart && toEnd) ? m.size() : entrySet().size();
1505         }
1506 
1507         public final boolean containsKey(Object key) {
1508             return inRange(key) && m.containsKey(key);
1509         }
1510 
1511         public final V put(K key, V value) {
1512             if (!inRange(key))
1513                 throw new IllegalArgumentException("key out of range");
1514             return m.put(key, value);
1515         }
1516 
1517         public final V get(Object key) {
1518             return !inRange(key) ? null :  m.get(key);
1519         }
1520 
1521         public final V remove(Object key) {
1522             return !inRange(key) ? null : m.remove(key);
1523         }
1524 
1525         public final Map.Entry<K,V> ceilingEntry(K key) {
1526             return exportEntry(subCeiling(key));
1527         }
1528 
1529         public final K ceilingKey(K key) {
1530             return keyOrNull(subCeiling(key));
1531         }
1532 
1533         public final Map.Entry<K,V> higherEntry(K key) {
1534             return exportEntry(subHigher(key));
1535         }
1536 
1537         public final K higherKey(K key) {
1538             return keyOrNull(subHigher(key));
1539         }
1540 
1541         public final Map.Entry<K,V> floorEntry(K key) {
1542             return exportEntry(subFloor(key));
1543         }
1544 
1545         public final K floorKey(K key) {
1546             return keyOrNull(subFloor(key));
1547         }
1548 
1549         public final Map.Entry<K,V> lowerEntry(K key) {
1550             return exportEntry(subLower(key));
1551         }
1552 
1553         public final K lowerKey(K key) {
1554             return keyOrNull(subLower(key));
1555         }
1556 
1557         public final K firstKey() {
1558             return key(subLowest());
1559         }
1560 
1561         public final K lastKey() {
1562             return key(subHighest());
1563         }
1564 
1565         public final Map.Entry<K,V> firstEntry() {
1566             return exportEntry(subLowest());
1567         }
1568 
1569         public final Map.Entry<K,V> lastEntry() {
1570             return exportEntry(subHighest());
1571         }
1572 
1573         public final Map.Entry<K,V> pollFirstEntry() {
1574             TreeMap.Entry<K,V> e = subLowest();
1575             Map.Entry<K,V> result = exportEntry(e);
1576             if (e != null)
1577                 m.deleteEntry(e);
1578             return result;
1579         }
1580 
1581         public final Map.Entry<K,V> pollLastEntry() {
1582             TreeMap.Entry<K,V> e = subHighest();
1583             Map.Entry<K,V> result = exportEntry(e);
1584             if (e != null)
1585                 m.deleteEntry(e);
1586             return result;
1587         }
1588 
1589         // Views
1590         transient NavigableMap<K,V> descendingMapView;
1591         transient EntrySetView entrySetView;
1592         transient KeySet<K> navigableKeySetView;
1593 
1594         public final NavigableSet<K> navigableKeySet() {
1595             KeySet<K> nksv = navigableKeySetView;
1596             return (nksv != null) ? nksv :
1597                 (navigableKeySetView = new TreeMap.KeySet<>(this));
1598         }
1599 
1600         public final Set<K> keySet() {
1601             return navigableKeySet();
1602         }
1603 
1604         public NavigableSet<K> descendingKeySet() {
1605             return descendingMap().navigableKeySet();
1606         }
1607 
1608         public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1609             return subMap(fromKey, true, toKey, false);
1610         }
1611 
1612         public final SortedMap<K,V> headMap(K toKey) {
1613             return headMap(toKey, false);
1614         }
1615 
1616         public final SortedMap<K,V> tailMap(K fromKey) {
1617             return tailMap(fromKey, true);
1618         }
1619 
1620         // View classes
1621 
1622         abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1623             private transient int size = -1, sizeModCount;
1624 
1625             public int size() {
1626                 if (fromStart && toEnd)
1627                     return m.size();
1628                 if (size == -1 || sizeModCount != m.modCount) {
1629                     sizeModCount = m.modCount;
1630                     size = 0;
1631                     Iterator<?> i = iterator();
1632                     while (i.hasNext()) {
1633                         size++;
1634                         i.next();
1635                     }
1636                 }
1637                 return size;
1638             }
1639 
1640             public boolean isEmpty() {
1641                 TreeMap.Entry<K,V> n = absLowest();
1642                 return n == null || tooHigh(n.key);
1643             }
1644 
1645             public boolean contains(Object o) {
1646                 if (!(o instanceof Map.Entry))
1647                     return false;
1648                 Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
1649                 Object key = entry.getKey();
1650                 if (!inRange(key))
1651                     return false;
1652                 TreeMap.Entry<?,?> node = m.getEntry(key);
1653                 return node != null &&
1654                     valEquals(node.getValue(), entry.getValue());
1655             }
1656 
1657             public boolean remove(Object o) {
1658                 if (!(o instanceof Map.Entry))
1659                     return false;
1660                 Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
1661                 Object key = entry.getKey();
1662                 if (!inRange(key))
1663                     return false;
1664                 TreeMap.Entry<K,V> node = m.getEntry(key);
1665                 if (node!=null && valEquals(node.getValue(),
1666                                             entry.getValue())) {
1667                     m.deleteEntry(node);
1668                     return true;
1669                 }
1670                 return false;
1671             }
1672         }
1673 
1674         /**
1675          * Iterators for SubMaps
1676          */
1677         abstract class SubMapIterator<T> implements Iterator<T> {
1678             TreeMap.Entry<K,V> lastReturned;
1679             TreeMap.Entry<K,V> next;
1680             final Object fenceKey;
1681             int expectedModCount;
1682 
1683             SubMapIterator(TreeMap.Entry<K,V> first,
1684                            TreeMap.Entry<K,V> fence) {
1685                 expectedModCount = m.modCount;
1686                 lastReturned = null;
1687                 next = first;
1688                 fenceKey = fence == null ? UNBOUNDED : fence.key;
1689             }
1690 
1691             public final boolean hasNext() {
1692                 return next != null && next.key != fenceKey;
1693             }
1694 
1695             final TreeMap.Entry<K,V> nextEntry() {
1696                 TreeMap.Entry<K,V> e = next;
1697                 if (e == null || e.key == fenceKey)
1698                     throw new NoSuchElementException();
1699                 if (m.modCount != expectedModCount)
1700                     throw new ConcurrentModificationException();
1701                 next = successor(e);
1702                 lastReturned = e;
1703                 return e;
1704             }
1705 
1706             final TreeMap.Entry<K,V> prevEntry() {
1707                 TreeMap.Entry<K,V> e = next;
1708                 if (e == null || e.key == fenceKey)
1709                     throw new NoSuchElementException();
1710                 if (m.modCount != expectedModCount)
1711                     throw new ConcurrentModificationException();
1712                 next = predecessor(e);
1713                 lastReturned = e;
1714                 return e;
1715             }
1716 
1717             final void removeAscending() {
1718                 if (lastReturned == null)
1719                     throw new IllegalStateException();
1720                 if (m.modCount != expectedModCount)
1721                     throw new ConcurrentModificationException();
1722                 // deleted entries are replaced by their successors
1723                 if (lastReturned.left != null && lastReturned.right != null)
1724                     next = lastReturned;
1725                 m.deleteEntry(lastReturned);
1726                 lastReturned = null;
1727                 expectedModCount = m.modCount;
1728             }
1729 
1730             final void removeDescending() {
1731                 if (lastReturned == null)
1732                     throw new IllegalStateException();
1733                 if (m.modCount != expectedModCount)
1734                     throw new ConcurrentModificationException();
1735                 m.deleteEntry(lastReturned);
1736                 lastReturned = null;
1737                 expectedModCount = m.modCount;
1738             }
1739 
1740         }
1741 
1742         final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1743             SubMapEntryIterator(TreeMap.Entry<K,V> first,
1744                                 TreeMap.Entry<K,V> fence) {
1745                 super(first, fence);
1746             }
1747             public Map.Entry<K,V> next() {
1748                 return nextEntry();
1749             }
1750             public void remove() {
1751                 removeAscending();
1752             }
1753         }
1754 
1755         final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1756             DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
1757                                           TreeMap.Entry<K,V> fence) {
1758                 super(last, fence);
1759             }
1760 
1761             public Map.Entry<K,V> next() {
1762                 return prevEntry();
1763             }
1764             public void remove() {
1765                 removeDescending();
1766             }
1767         }
1768 
1769         // Implement minimal Spliterator as KeySpliterator backup
1770         final class SubMapKeyIterator extends SubMapIterator<K>
1771             implements Spliterator<K> {
1772             SubMapKeyIterator(TreeMap.Entry<K,V> first,
1773                               TreeMap.Entry<K,V> fence) {
1774                 super(first, fence);
1775             }
1776             public K next() {
1777                 return nextEntry().key;
1778             }
1779             public void remove() {
1780                 removeAscending();
1781             }
1782             public Spliterator<K> trySplit() {
1783                 return null;
1784             }
1785             public void forEachRemaining(Consumer<? super K> action) {
1786                 while (hasNext())
1787                     action.accept(next());
1788             }
1789             public boolean tryAdvance(Consumer<? super K> action) {
1790                 if (hasNext()) {
1791                     action.accept(next());
1792                     return true;
1793                 }
1794                 return false;
1795             }
1796             public long estimateSize() {
1797                 return Long.MAX_VALUE;
1798             }
1799             public int characteristics() {
1800                 return Spliterator.DISTINCT | Spliterator.ORDERED |
1801                     Spliterator.SORTED;
1802             }
1803             public final Comparator<? super K>  getComparator() {
1804                 return NavigableSubMap.this.comparator();
1805             }
1806         }
1807 
1808         final class DescendingSubMapKeyIterator extends SubMapIterator<K>
1809             implements Spliterator<K> {
1810             DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
1811                                         TreeMap.Entry<K,V> fence) {
1812                 super(last, fence);
1813             }
1814             public K next() {
1815                 return prevEntry().key;
1816             }
1817             public void remove() {
1818                 removeDescending();
1819             }
1820             public Spliterator<K> trySplit() {
1821                 return null;
1822             }
1823             public void forEachRemaining(Consumer<? super K> action) {
1824                 while (hasNext())
1825                     action.accept(next());
1826             }
1827             public boolean tryAdvance(Consumer<? super K> action) {
1828                 if (hasNext()) {
1829                     action.accept(next());
1830                     return true;
1831                 }
1832                 return false;
1833             }
1834             public long estimateSize() {
1835                 return Long.MAX_VALUE;
1836             }
1837             public int characteristics() {
1838                 return Spliterator.DISTINCT | Spliterator.ORDERED;
1839             }
1840         }
1841     }
1842 
1843     /**
1844      * @serial include
1845      */
1846     static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1847         private static final long serialVersionUID = 912986545866124060L;
1848 
1849         AscendingSubMap(TreeMap<K,V> m,
1850                         boolean fromStart, K lo, boolean loInclusive,
1851                         boolean toEnd,     K hi, boolean hiInclusive) {
1852             super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1853         }
1854 
1855         public Comparator<? super K> comparator() {
1856             return m.comparator();
1857         }
1858 
1859         public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1860                                         K toKey,   boolean toInclusive) {
1861             if (!inRange(fromKey, fromInclusive))
1862                 throw new IllegalArgumentException("fromKey out of range");
1863             if (!inRange(toKey, toInclusive))
1864                 throw new IllegalArgumentException("toKey out of range");
1865             return new AscendingSubMap<>(m,
1866                                          false, fromKey, fromInclusive,
1867                                          false, toKey,   toInclusive);
1868         }
1869 
1870         public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1871             if (!inRange(toKey, inclusive))
1872                 throw new IllegalArgumentException("toKey out of range");
1873             return new AscendingSubMap<>(m,
1874                                          fromStart, lo,    loInclusive,
1875                                          false,     toKey, inclusive);
1876         }
1877 
1878         public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
1879             if (!inRange(fromKey, inclusive))
1880                 throw new IllegalArgumentException("fromKey out of range");
1881             return new AscendingSubMap<>(m,
1882                                          false, fromKey, inclusive,
1883                                          toEnd, hi,      hiInclusive);
1884         }
1885 
1886         public NavigableMap<K,V> descendingMap() {
1887             NavigableMap<K,V> mv = descendingMapView;
1888             return (mv != null) ? mv :
1889                 (descendingMapView =
1890                  new DescendingSubMap<>(m,
1891                                         fromStart, lo, loInclusive,
1892                                         toEnd,     hi, hiInclusive));
1893         }
1894 
1895         Iterator<K> keyIterator() {
1896             return new SubMapKeyIterator(absLowest(), absHighFence());
1897         }
1898 
1899         Spliterator<K> keySpliterator() {
1900             return new SubMapKeyIterator(absLowest(), absHighFence());
1901         }
1902 
1903         Iterator<K> descendingKeyIterator() {
1904             return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1905         }
1906 
1907         final class AscendingEntrySetView extends EntrySetView {
1908             public Iterator<Map.Entry<K,V>> iterator() {
1909                 return new SubMapEntryIterator(absLowest(), absHighFence());
1910             }
1911         }
1912 
1913         public Set<Map.Entry<K,V>> entrySet() {
1914             EntrySetView es = entrySetView;
1915             return (es != null) ? es : (entrySetView = new AscendingEntrySetView());
1916         }
1917 
1918         TreeMap.Entry<K,V> subLowest()       { return absLowest(); }
1919         TreeMap.Entry<K,V> subHighest()      { return absHighest(); }
1920         TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); }
1921         TreeMap.Entry<K,V> subHigher(K key)  { return absHigher(key); }
1922         TreeMap.Entry<K,V> subFloor(K key)   { return absFloor(key); }
1923         TreeMap.Entry<K,V> subLower(K key)   { return absLower(key); }
1924     }
1925 
1926     /**
1927      * @serial include
1928      */
1929     static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
1930         private static final long serialVersionUID = 912986545866120460L;
1931         DescendingSubMap(TreeMap<K,V> m,
1932                         boolean fromStart, K lo, boolean loInclusive,
1933                         boolean toEnd,     K hi, boolean hiInclusive) {
1934             super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1935         }
1936 
1937         private final Comparator<? super K> reverseComparator =
1938             Collections.reverseOrder(m.comparator);
1939 
1940         public Comparator<? super K> comparator() {
1941             return reverseComparator;
1942         }
1943 
1944         public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1945                                         K toKey,   boolean toInclusive) {
1946             if (!inRange(fromKey, fromInclusive))
1947                 throw new IllegalArgumentException("fromKey out of range");
1948             if (!inRange(toKey, toInclusive))
1949                 throw new IllegalArgumentException("toKey out of range");
1950             return new DescendingSubMap<>(m,
1951                                           false, toKey,   toInclusive,
1952                                           false, fromKey, fromInclusive);
1953         }
1954 
1955         public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1956             if (!inRange(toKey, inclusive))
1957                 throw new IllegalArgumentException("toKey out of range");
1958             return new DescendingSubMap<>(m,
1959                                           false, toKey, inclusive,
1960                                           toEnd, hi,    hiInclusive);
1961         }
1962 
1963         public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
1964             if (!inRange(fromKey, inclusive))
1965                 throw new IllegalArgumentException("fromKey out of range");
1966             return new DescendingSubMap<>(m,
1967                                           fromStart, lo, loInclusive,
1968                                           false, fromKey, inclusive);
1969         }
1970 
1971         public NavigableMap<K,V> descendingMap() {
1972             NavigableMap<K,V> mv = descendingMapView;
1973             return (mv != null) ? mv :
1974                 (descendingMapView =
1975                  new AscendingSubMap<>(m,
1976                                        fromStart, lo, loInclusive,
1977                                        toEnd,     hi, hiInclusive));
1978         }
1979 
1980         Iterator<K> keyIterator() {
1981             return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1982         }
1983 
1984         Spliterator<K> keySpliterator() {
1985             return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1986         }
1987 
1988         Iterator<K> descendingKeyIterator() {
1989             return new SubMapKeyIterator(absLowest(), absHighFence());
1990         }
1991 
1992         final class DescendingEntrySetView extends EntrySetView {
1993             public Iterator<Map.Entry<K,V>> iterator() {
1994                 return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
1995             }
1996         }
1997 
1998         public Set<Map.Entry<K,V>> entrySet() {
1999             EntrySetView es = entrySetView;
2000             return (es != null) ? es : (entrySetView = new DescendingEntrySetView());
2001         }
2002 
2003         TreeMap.Entry<K,V> subLowest()       { return absHighest(); }
2004         TreeMap.Entry<K,V> subHighest()      { return absLowest(); }
2005         TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
2006         TreeMap.Entry<K,V> subHigher(K key)  { return absLower(key); }
2007         TreeMap.Entry<K,V> subFloor(K key)   { return absCeiling(key); }
2008         TreeMap.Entry<K,V> subLower(K key)   { return absHigher(key); }
2009     }
2010 
2011     /**
2012      * This class exists solely for the sake of serialization
2013      * compatibility with previous releases of TreeMap that did not
2014      * support NavigableMap.  It translates an old-version SubMap into
2015      * a new-version AscendingSubMap. This class is never otherwise
2016      * used.
2017      *
2018      * @serial include
2019      */
2020     private class SubMap extends AbstractMap<K,V>
2021         implements SortedMap<K,V>, java.io.Serializable {
2022         private static final long serialVersionUID = -6520786458950516097L;
2023         private boolean fromStart = false, toEnd = false;
2024         private K fromKey, toKey;
2025         private Object readResolve() {
2026             return new AscendingSubMap<>(TreeMap.this,
2027                                          fromStart, fromKey, true,
2028                                          toEnd, toKey, false);
2029         }
2030         public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
2031         public K lastKey() { throw new InternalError(); }
2032         public K firstKey() { throw new InternalError(); }
2033         public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
2034         public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
2035         public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
2036         public Comparator<? super K> comparator() { throw new InternalError(); }
2037     }
2038 
2039 
2040     // Red-black mechanics
2041 
2042     private static final boolean RED   = false;
2043     private static final boolean BLACK = true;
2044 
2045     /**
2046      * Node in the Tree.  Doubles as a means to pass key-value pairs back to
2047      * user (see Map.Entry).
2048      */
2049 
2050     static final class Entry<K,V> implements Map.Entry<K,V> {
2051         K key;
2052         V value;
2053         Entry<K,V> left;
2054         Entry<K,V> right;
2055         Entry<K,V> parent;
2056         boolean color = BLACK;
2057 
2058         /**
2059          * Make a new cell with given key, value, and parent, and with
2060          * {@code null} child links, and BLACK color.
2061          */
2062         Entry(K key, V value, Entry<K,V> parent) {
2063             this.key = key;
2064             this.value = value;
2065             this.parent = parent;
2066         }
2067 
2068         /**
2069          * Returns the key.
2070          *
2071          * @return the key
2072          */
2073         public K getKey() {
2074             return key;
2075         }
2076 
2077         /**
2078          * Returns the value associated with the key.
2079          *
2080          * @return the value associated with the key
2081          */
2082         public V getValue() {
2083             return value;
2084         }
2085 
2086         /**
2087          * Replaces the value currently associated with the key with the given
2088          * value.
2089          *
2090          * @return the value associated with the key before this method was
2091          *         called
2092          */
2093         public V setValue(V value) {
2094             V oldValue = this.value;
2095             this.value = value;
2096             return oldValue;
2097         }
2098 
2099         public boolean equals(Object o) {
2100             if (!(o instanceof Map.Entry))
2101                 return false;
2102             Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2103 
2104             return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
2105         }
2106 
2107         public int hashCode() {
2108             int keyHash = (key==null ? 0 : key.hashCode());
2109             int valueHash = (value==null ? 0 : value.hashCode());
2110             return keyHash ^ valueHash;
2111         }
2112 
2113         public String toString() {
2114             return key + "=" + value;
2115         }
2116     }
2117 
2118     /**
2119      * Returns the first Entry in the TreeMap (according to the TreeMap's
2120      * key-sort function).  Returns null if the TreeMap is empty.
2121      */
2122     final Entry<K,V> getFirstEntry() {
2123         Entry<K,V> p = root;
2124         if (p != null)
2125             while (p.left != null)
2126                 p = p.left;
2127         return p;
2128     }
2129 
2130     /**
2131      * Returns the last Entry in the TreeMap (according to the TreeMap's
2132      * key-sort function).  Returns null if the TreeMap is empty.
2133      */
2134     final Entry<K,V> getLastEntry() {
2135         Entry<K,V> p = root;
2136         if (p != null)
2137             while (p.right != null)
2138                 p = p.right;
2139         return p;
2140     }
2141 
2142     /**
2143      * Returns the successor of the specified Entry, or null if no such.
2144      */
2145     static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
2146         if (t == null)
2147             return null;
2148         else if (t.right != null) {
2149             Entry<K,V> p = t.right;
2150             while (p.left != null)
2151                 p = p.left;
2152             return p;
2153         } else {
2154             Entry<K,V> p = t.parent;
2155             Entry<K,V> ch = t;
2156             while (p != null && ch == p.right) {
2157                 ch = p;
2158                 p = p.parent;
2159             }
2160             return p;
2161         }
2162     }
2163 
2164     /**
2165      * Returns the predecessor of the specified Entry, or null if no such.
2166      */
2167     static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {
2168         if (t == null)
2169             return null;
2170         else if (t.left != null) {
2171             Entry<K,V> p = t.left;
2172             while (p.right != null)
2173                 p = p.right;
2174             return p;
2175         } else {
2176             Entry<K,V> p = t.parent;
2177             Entry<K,V> ch = t;
2178             while (p != null && ch == p.left) {
2179                 ch = p;
2180                 p = p.parent;
2181             }
2182             return p;
2183         }
2184     }
2185 
2186     /**
2187      * Balancing operations.
2188      *
2189      * Implementations of rebalancings during insertion and deletion are
2190      * slightly different than the CLR version.  Rather than using dummy
2191      * nilnodes, we use a set of accessors that deal properly with null.  They
2192      * are used to avoid messiness surrounding nullness checks in the main
2193      * algorithms.
2194      */
2195 
2196     private static <K,V> boolean colorOf(Entry<K,V> p) {
2197         return (p == null ? BLACK : p.color);
2198     }
2199 
2200     private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) {
2201         return (p == null ? null: p.parent);
2202     }
2203 
2204     private static <K,V> void setColor(Entry<K,V> p, boolean c) {
2205         if (p != null)
2206             p.color = c;
2207     }
2208 
2209     private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) {
2210         return (p == null) ? null: p.left;
2211     }
2212 
2213     private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) {
2214         return (p == null) ? null: p.right;
2215     }
2216 
2217     /** From CLR */
2218     private void rotateLeft(Entry<K,V> p) {
2219         if (p != null) {
2220             Entry<K,V> r = p.right;
2221             p.right = r.left;
2222             if (r.left != null)
2223                 r.left.parent = p;
2224             r.parent = p.parent;
2225             if (p.parent == null)
2226                 root = r;
2227             else if (p.parent.left == p)
2228                 p.parent.left = r;
2229             else
2230                 p.parent.right = r;
2231             r.left = p;
2232             p.parent = r;
2233         }
2234     }
2235 
2236     /** From CLR */
2237     private void rotateRight(Entry<K,V> p) {
2238         if (p != null) {
2239             Entry<K,V> l = p.left;
2240             p.left = l.right;
2241             if (l.right != null) l.right.parent = p;
2242             l.parent = p.parent;
2243             if (p.parent == null)
2244                 root = l;
2245             else if (p.parent.right == p)
2246                 p.parent.right = l;
2247             else p.parent.left = l;
2248             l.right = p;
2249             p.parent = l;
2250         }
2251     }
2252 
2253     /** From CLR */
2254     private void fixAfterInsertion(Entry<K,V> x) {
2255         x.color = RED;
2256 
2257         while (x != null && x != root && x.parent.color == RED) {
2258             if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
2259                 Entry<K,V> y = rightOf(parentOf(parentOf(x)));
2260                 if (colorOf(y) == RED) {
2261                     setColor(parentOf(x), BLACK);
2262                     setColor(y, BLACK);
2263                     setColor(parentOf(parentOf(x)), RED);
2264                     x = parentOf(parentOf(x));
2265                 } else {
2266                     if (x == rightOf(parentOf(x))) {
2267                         x = parentOf(x);
2268                         rotateLeft(x);
2269                     }
2270                     setColor(parentOf(x), BLACK);
2271                     setColor(parentOf(parentOf(x)), RED);
2272                     rotateRight(parentOf(parentOf(x)));
2273                 }
2274             } else {
2275                 Entry<K,V> y = leftOf(parentOf(parentOf(x)));
2276                 if (colorOf(y) == RED) {
2277                     setColor(parentOf(x), BLACK);
2278                     setColor(y, BLACK);
2279                     setColor(parentOf(parentOf(x)), RED);
2280                     x = parentOf(parentOf(x));
2281                 } else {
2282                     if (x == leftOf(parentOf(x))) {
2283                         x = parentOf(x);
2284                         rotateRight(x);
2285                     }
2286                     setColor(parentOf(x), BLACK);
2287                     setColor(parentOf(parentOf(x)), RED);
2288                     rotateLeft(parentOf(parentOf(x)));
2289                 }
2290             }
2291         }
2292         root.color = BLACK;
2293     }
2294 
2295     /**
2296      * Delete node p, and then rebalance the tree.
2297      */
2298     private void deleteEntry(Entry<K,V> p) {
2299         modCount++;
2300         size--;
2301 
2302         // If strictly internal, copy successor's element to p and then make p
2303         // point to successor.
2304         if (p.left != null && p.right != null) {
2305             Entry<K,V> s = successor(p);
2306             p.key = s.key;
2307             p.value = s.value;
2308             p = s;
2309         } // p has 2 children
2310 
2311         // Start fixup at replacement node, if it exists.
2312         Entry<K,V> replacement = (p.left != null ? p.left : p.right);
2313 
2314         if (replacement != null) {
2315             // Link replacement to parent
2316             replacement.parent = p.parent;
2317             if (p.parent == null)
2318                 root = replacement;
2319             else if (p == p.parent.left)
2320                 p.parent.left  = replacement;
2321             else
2322                 p.parent.right = replacement;
2323 
2324             // Null out links so they are OK to use by fixAfterDeletion.
2325             p.left = p.right = p.parent = null;
2326 
2327             // Fix replacement
2328             if (p.color == BLACK)
2329                 fixAfterDeletion(replacement);
2330         } else if (p.parent == null) { // return if we are the only node.
2331             root = null;
2332         } else { //  No children. Use self as phantom replacement and unlink.
2333             if (p.color == BLACK)
2334                 fixAfterDeletion(p);
2335 
2336             if (p.parent != null) {
2337                 if (p == p.parent.left)
2338                     p.parent.left = null;
2339                 else if (p == p.parent.right)
2340                     p.parent.right = null;
2341                 p.parent = null;
2342             }
2343         }
2344     }
2345 
2346     /** From CLR */
2347     private void fixAfterDeletion(Entry<K,V> x) {
2348         while (x != root && colorOf(x) == BLACK) {
2349             if (x == leftOf(parentOf(x))) {
2350                 Entry<K,V> sib = rightOf(parentOf(x));
2351 
2352                 if (colorOf(sib) == RED) {
2353                     setColor(sib, BLACK);
2354                     setColor(parentOf(x), RED);
2355                     rotateLeft(parentOf(x));
2356                     sib = rightOf(parentOf(x));
2357                 }
2358 
2359                 if (colorOf(leftOf(sib))  == BLACK &&
2360                     colorOf(rightOf(sib)) == BLACK) {
2361                     setColor(sib, RED);
2362                     x = parentOf(x);
2363                 } else {
2364                     if (colorOf(rightOf(sib)) == BLACK) {
2365                         setColor(leftOf(sib), BLACK);
2366                         setColor(sib, RED);
2367                         rotateRight(sib);
2368                         sib = rightOf(parentOf(x));
2369                     }
2370                     setColor(sib, colorOf(parentOf(x)));
2371                     setColor(parentOf(x), BLACK);
2372                     setColor(rightOf(sib), BLACK);
2373                     rotateLeft(parentOf(x));
2374                     x = root;
2375                 }
2376             } else { // symmetric
2377                 Entry<K,V> sib = leftOf(parentOf(x));
2378 
2379                 if (colorOf(sib) == RED) {
2380                     setColor(sib, BLACK);
2381                     setColor(parentOf(x), RED);
2382                     rotateRight(parentOf(x));
2383                     sib = leftOf(parentOf(x));
2384                 }
2385 
2386                 if (colorOf(rightOf(sib)) == BLACK &&
2387                     colorOf(leftOf(sib)) == BLACK) {
2388                     setColor(sib, RED);
2389                     x = parentOf(x);
2390                 } else {
2391                     if (colorOf(leftOf(sib)) == BLACK) {
2392                         setColor(rightOf(sib), BLACK);
2393                         setColor(sib, RED);
2394                         rotateLeft(sib);
2395                         sib = leftOf(parentOf(x));
2396                     }
2397                     setColor(sib, colorOf(parentOf(x)));
2398                     setColor(parentOf(x), BLACK);
2399                     setColor(leftOf(sib), BLACK);
2400                     rotateRight(parentOf(x));
2401                     x = root;
2402                 }
2403             }
2404         }
2405 
2406         setColor(x, BLACK);
2407     }
2408 
2409     private static final long serialVersionUID = 919286545866124006L;
2410 
2411     /**
2412      * Save the state of the {@code TreeMap} instance to a stream (i.e.,
2413      * serialize it).
2414      *
2415      * @serialData The <em>size</em> of the TreeMap (the number of key-value
2416      *             mappings) is emitted (int), followed by the key (Object)
2417      *             and value (Object) for each key-value mapping represented
2418      *             by the TreeMap. The key-value mappings are emitted in
2419      *             key-order (as determined by the TreeMap's Comparator,
2420      *             or by the keys' natural ordering if the TreeMap has no
2421      *             Comparator).
2422      */
2423     private void writeObject(java.io.ObjectOutputStream s)
2424         throws java.io.IOException {
2425         // Write out the Comparator and any hidden stuff
2426         s.defaultWriteObject();
2427 
2428         // Write out size (number of Mappings)
2429         s.writeInt(size);
2430 
2431         // Write out keys and values (alternating)
2432         for (Map.Entry<K, V> e : entrySet()) {
2433             s.writeObject(e.getKey());
2434             s.writeObject(e.getValue());
2435         }
2436     }
2437 
2438     /**
2439      * Reconstitute the {@code TreeMap} instance from a stream (i.e.,
2440      * deserialize it).
2441      */
2442     private void readObject(final java.io.ObjectInputStream s)
2443         throws java.io.IOException, ClassNotFoundException {
2444         // Read in the Comparator and any hidden stuff
2445         s.defaultReadObject();
2446 
2447         // Read in size
2448         int size = s.readInt();
2449 
2450         buildFromSorted(size, null, s, null);
2451     }
2452 
2453     /** Intended to be called only from TreeSet.readObject */
2454     void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2455         throws java.io.IOException, ClassNotFoundException {
2456         buildFromSorted(size, null, s, defaultVal);
2457     }
2458 
2459     /** Intended to be called only from TreeSet.addAll */
2460     void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2461         try {
2462             buildFromSorted(set.size(), set.iterator(), null, defaultVal);
2463         } catch (java.io.IOException | ClassNotFoundException cannotHappen) {
2464         }
2465     }
2466 
2467 
2468     /**
2469      * Linear time tree building algorithm from sorted data.  Can accept keys
2470      * and/or values from iterator or stream. This leads to too many
2471      * parameters, but seems better than alternatives.  The four formats
2472      * that this method accepts are:
2473      *
2474      *    1) An iterator of Map.Entries.  (it != null, defaultVal == null).
2475      *    2) An iterator of keys.         (it != null, defaultVal != null).
2476      *    3) A stream of alternating serialized keys and values.
2477      *                                   (it == null, defaultVal == null).
2478      *    4) A stream of serialized keys. (it == null, defaultVal != null).
2479      *
2480      * It is assumed that the comparator of the TreeMap is already set prior
2481      * to calling this method.
2482      *
2483      * @param size the number of keys (or key-value pairs) to be read from
2484      *        the iterator or stream
2485      * @param it If non-null, new entries are created from entries
2486      *        or keys read from this iterator.
2487      * @param str If non-null, new entries are created from keys and
2488      *        possibly values read from this stream in serialized form.
2489      *        Exactly one of it and str should be non-null.
2490      * @param defaultVal if non-null, this default value is used for
2491      *        each value in the map.  If null, each value is read from
2492      *        iterator or stream, as described above.
2493      * @throws java.io.IOException propagated from stream reads. This cannot
2494      *         occur if str is null.
2495      * @throws ClassNotFoundException propagated from readObject.
2496      *         This cannot occur if str is null.
2497      */
2498     private void buildFromSorted(int size, Iterator<?> it,
2499                                  java.io.ObjectInputStream str,
2500                                  V defaultVal)
2501         throws  java.io.IOException, ClassNotFoundException {
2502         this.size = size;
2503         root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
2504                                it, str, defaultVal);
2505     }
2506 
2507     /**
2508      * Recursive "helper method" that does the real work of the
2509      * previous method.  Identically named parameters have
2510      * identical definitions.  Additional parameters are documented below.
2511      * It is assumed that the comparator and size fields of the TreeMap are
2512      * already set prior to calling this method.  (It ignores both fields.)
2513      *
2514      * @param level the current level of tree. Initial call should be 0.
2515      * @param lo the first element index of this subtree. Initial should be 0.
2516      * @param hi the last element index of this subtree.  Initial should be
2517      *        size-1.
2518      * @param redLevel the level at which nodes should be red.
2519      *        Must be equal to computeRedLevel for tree of this size.
2520      */
2521     @SuppressWarnings("unchecked")
2522     private final Entry<K,V> buildFromSorted(int level, int lo, int hi,
2523                                              int redLevel,
2524                                              Iterator<?> it,
2525                                              java.io.ObjectInputStream str,
2526                                              V defaultVal)
2527         throws  java.io.IOException, ClassNotFoundException {
2528         /*
2529          * Strategy: The root is the middlemost element. To get to it, we
2530          * have to first recursively construct the entire left subtree,
2531          * so as to grab all of its elements. We can then proceed with right
2532          * subtree.
2533          *
2534          * The lo and hi arguments are the minimum and maximum
2535          * indices to pull out of the iterator or stream for current subtree.
2536          * They are not actually indexed, we just proceed sequentially,
2537          * ensuring that items are extracted in corresponding order.
2538          */
2539 
2540         if (hi < lo) return null;
2541 
2542         int mid = (lo + hi) >>> 1;
2543 
2544         Entry<K,V> left  = null;
2545         if (lo < mid)
2546             left = buildFromSorted(level+1, lo, mid - 1, redLevel,
2547                                    it, str, defaultVal);
2548 
2549         // extract key and/or value from iterator or stream
2550         K key;
2551         V value;
2552         if (it != null) {
2553             if (defaultVal==null) {
2554                 Map.Entry<?,?> entry = (Map.Entry<?,?>)it.next();
2555                 key = (K)entry.getKey();
2556                 value = (V)entry.getValue();
2557             } else {
2558                 key = (K)it.next();
2559                 value = defaultVal;
2560             }
2561         } else { // use stream
2562             key = (K) str.readObject();
2563             value = (defaultVal != null ? defaultVal : (V) str.readObject());
2564         }
2565 
2566         Entry<K,V> middle =  new Entry<>(key, value, null);
2567 
2568         // color nodes in non-full bottommost level red
2569         if (level == redLevel)
2570             middle.color = RED;
2571 
2572         if (left != null) {
2573             middle.left = left;
2574             left.parent = middle;
2575         }
2576 
2577         if (mid < hi) {
2578             Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
2579                                                it, str, defaultVal);
2580             middle.right = right;
2581             right.parent = middle;
2582         }
2583 
2584         return middle;
2585     }
2586 
2587     /**
2588      * Finds the level down to which to assign all nodes BLACK.  This is the
2589      * last `full' level of the complete binary tree produced by buildTree.
2590      * The remaining nodes are colored RED. (This makes a `nice' set of
2591      * color assignments wrt future insertions.) This level number is
2592      * computed by finding the number of splits needed to reach the zeroeth
2593      * node.
2594      *
2595      * @param size the (non-negative) number of keys in the tree to be built
2596      */
2597     private static int computeRedLevel(int size) {
2598         return 31 - Integer.numberOfLeadingZeros(size + 1);
2599     }
2600 
2601     /**
2602      * Currently, we support Spliterator-based versions only for the
2603      * full map, in either plain of descending form, otherwise relying
2604      * on defaults because size estimation for submaps would dominate
2605      * costs. The type tests needed to check these for key views are
2606      * not very nice but avoid disrupting existing class
2607      * structures. Callers must use plain default spliterators if this
2608      * returns null.
2609      */
2610     static <K> Spliterator<K> keySpliteratorFor(NavigableMap<K,?> m) {
2611         if (m instanceof TreeMap) {
2612             @SuppressWarnings("unchecked") TreeMap<K,Object> t =
2613                 (TreeMap<K,Object>) m;
2614             return t.keySpliterator();
2615         }
2616         if (m instanceof DescendingSubMap) {
2617             @SuppressWarnings("unchecked") DescendingSubMap<K,?> dm =
2618                 (DescendingSubMap<K,?>) m;
2619             TreeMap<K,?> tm = dm.m;
2620             if (dm == tm.descendingMap) {
2621                 @SuppressWarnings("unchecked") TreeMap<K,Object> t =
2622                     (TreeMap<K,Object>) tm;
2623                 return t.descendingKeySpliterator();
2624             }
2625         }
2626         @SuppressWarnings("unchecked") NavigableSubMap<K,?> sm =
2627             (NavigableSubMap<K,?>) m;
2628         return sm.keySpliterator();
2629     }
2630 
2631     final Spliterator<K> keySpliterator() {
2632         return new KeySpliterator<>(this, null, null, 0, -1, 0);
2633     }
2634 
2635     final Spliterator<K> descendingKeySpliterator() {
2636         return new DescendingKeySpliterator<>(this, null, null, 0, -2, 0);
2637     }
2638 
2639     /**
2640      * Base class for spliterators.  Iteration starts at a given
2641      * origin and continues up to but not including a given fence (or
2642      * null for end).  At top-level, for ascending cases, the first
2643      * split uses the root as left-fence/right-origin. From there,
2644      * right-hand splits replace the current fence with its left
2645      * child, also serving as origin for the split-off spliterator.
2646      * Left-hands are symmetric. Descending versions place the origin
2647      * at the end and invert ascending split rules.  This base class
2648      * is non-committal about directionality, or whether the top-level
2649      * spliterator covers the whole tree. This means that the actual
2650      * split mechanics are located in subclasses. Some of the subclass
2651      * trySplit methods are identical (except for return types), but
2652      * not nicely factorable.
2653      *
2654      * Currently, subclass versions exist only for the full map
2655      * (including descending keys via its descendingMap).  Others are
2656      * possible but currently not worthwhile because submaps require
2657      * O(n) computations to determine size, which substantially limits
2658      * potential speed-ups of using custom Spliterators versus default
2659      * mechanics.
2660      *
2661      * To boostrap initialization, external constructors use
2662      * negative size estimates: -1 for ascend, -2 for descend.
2663      */
2664     static class TreeMapSpliterator<K,V> {
2665         final TreeMap<K,V> tree;
2666         TreeMap.Entry<K,V> current; // traverser; initially first node in range
2667         TreeMap.Entry<K,V> fence;   // one past last, or null
2668         int side;                   // 0: top, -1: is a left split, +1: right
2669         int est;                    // size estimate (exact only for top-level)
2670         int expectedModCount;       // for CME checks
2671 
2672         TreeMapSpliterator(TreeMap<K,V> tree,
2673                            TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence,
2674                            int side, int est, int expectedModCount) {
2675             this.tree = tree;
2676             this.current = origin;
2677             this.fence = fence;
2678             this.side = side;
2679             this.est = est;
2680             this.expectedModCount = expectedModCount;
2681         }
2682 
2683         final int getEstimate() { // force initialization
2684             int s; TreeMap<K,V> t;
2685             if ((s = est) < 0) {
2686                 if ((t = tree) != null) {
2687                     current = (s == -1) ? t.getFirstEntry() : t.getLastEntry();
2688                     s = est = t.size;
2689                     expectedModCount = t.modCount;
2690                 }
2691                 else
2692                     s = est = 0;
2693             }
2694             return s;
2695         }
2696 
2697         public final long estimateSize() {
2698             return (long)getEstimate();
2699         }
2700     }
2701 
2702     static final class KeySpliterator<K,V>
2703         extends TreeMapSpliterator<K,V>
2704         implements Spliterator<K> {
2705         KeySpliterator(TreeMap<K,V> tree,
2706                        TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence,
2707                        int side, int est, int expectedModCount) {
2708             super(tree, origin, fence, side, est, expectedModCount);
2709         }
2710 
2711         public KeySpliterator<K,V> trySplit() {
2712             if (est < 0)
2713                 getEstimate(); // force initialization
2714             int d = side;
2715             TreeMap.Entry<K,V> e = current, f = fence,
2716                 s = ((e == null || e == f) ? null :      // empty
2717                      (d == 0)              ? tree.root : // was top
2718                      (d >  0)              ? e.right :   // was right
2719                      (d <  0 && f != null) ? f.left :    // was left
2720                      null);
2721             if (s != null && s != e && s != f &&
2722                 tree.compare(e.key, s.key) < 0) {        // e not already past s
2723                 side = 1;
2724                 return new KeySpliterator<>
2725                     (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2726             }
2727             return null;
2728         }
2729 
2730         public void forEachRemaining(Consumer<? super K> action) {
2731             if (action == null)
2732                 throw new NullPointerException();
2733             if (est < 0)
2734                 getEstimate(); // force initialization
2735             TreeMap.Entry<K,V> f = fence, e, p, pl;
2736             if ((e = current) != null && e != f) {
2737                 current = f; // exhaust
2738                 do {
2739                     action.accept(e.key);
2740                     if ((p = e.right) != null) {
2741                         while ((pl = p.left) != null)
2742                             p = pl;
2743                     }
2744                     else {
2745                         while ((p = e.parent) != null && e == p.right)
2746                             e = p;
2747                     }
2748                 } while ((e = p) != null && e != f);
2749                 if (tree.modCount != expectedModCount)
2750                     throw new ConcurrentModificationException();
2751             }
2752         }
2753 
2754         public boolean tryAdvance(Consumer<? super K> action) {
2755             TreeMap.Entry<K,V> e;
2756             if (action == null)
2757                 throw new NullPointerException();
2758             if (est < 0)
2759                 getEstimate(); // force initialization
2760             if ((e = current) == null || e == fence)
2761                 return false;
2762             current = successor(e);
2763             action.accept(e.key);
2764             if (tree.modCount != expectedModCount)
2765                 throw new ConcurrentModificationException();
2766             return true;
2767         }
2768 
2769         public int characteristics() {
2770             return (side == 0 ? Spliterator.SIZED : 0) |
2771                 Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED;
2772         }
2773 
2774         public final Comparator<? super K>  getComparator() {
2775             return tree.comparator;
2776         }
2777 
2778     }
2779 
2780     static final class DescendingKeySpliterator<K,V>
2781         extends TreeMapSpliterator<K,V>
2782         implements Spliterator<K> {
2783         DescendingKeySpliterator(TreeMap<K,V> tree,
2784                                  TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence,
2785                                  int side, int est, int expectedModCount) {
2786             super(tree, origin, fence, side, est, expectedModCount);
2787         }
2788 
2789         public DescendingKeySpliterator<K,V> trySplit() {
2790             if (est < 0)
2791                 getEstimate(); // force initialization
2792             int d = side;
2793             TreeMap.Entry<K,V> e = current, f = fence,
2794                     s = ((e == null || e == f) ? null :      // empty
2795                          (d == 0)              ? tree.root : // was top
2796                          (d <  0)              ? e.left :    // was left
2797                          (d >  0 && f != null) ? f.right :   // was right
2798                          null);
2799             if (s != null && s != e && s != f &&
2800                 tree.compare(e.key, s.key) > 0) {       // e not already past s
2801                 side = 1;
2802                 return new DescendingKeySpliterator<>
2803                         (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2804             }
2805             return null;
2806         }
2807 
2808         public void forEachRemaining(Consumer<? super K> action) {
2809             if (action == null)
2810                 throw new NullPointerException();
2811             if (est < 0)
2812                 getEstimate(); // force initialization
2813             TreeMap.Entry<K,V> f = fence, e, p, pr;
2814             if ((e = current) != null && e != f) {
2815                 current = f; // exhaust
2816                 do {
2817                     action.accept(e.key);
2818                     if ((p = e.left) != null) {
2819                         while ((pr = p.right) != null)
2820                             p = pr;
2821                     }
2822                     else {
2823                         while ((p = e.parent) != null && e == p.left)
2824                             e = p;
2825                     }
2826                 } while ((e = p) != null && e != f);
2827                 if (tree.modCount != expectedModCount)
2828                     throw new ConcurrentModificationException();
2829             }
2830         }
2831 
2832         public boolean tryAdvance(Consumer<? super K> action) {
2833             TreeMap.Entry<K,V> e;
2834             if (action == null)
2835                 throw new NullPointerException();
2836             if (est < 0)
2837                 getEstimate(); // force initialization
2838             if ((e = current) == null || e == fence)
2839                 return false;
2840             current = predecessor(e);
2841             action.accept(e.key);
2842             if (tree.modCount != expectedModCount)
2843                 throw new ConcurrentModificationException();
2844             return true;
2845         }
2846 
2847         public int characteristics() {
2848             return (side == 0 ? Spliterator.SIZED : 0) |
2849                 Spliterator.DISTINCT | Spliterator.ORDERED;
2850         }
2851     }
2852 
2853     static final class ValueSpliterator<K,V>
2854             extends TreeMapSpliterator<K,V>
2855             implements Spliterator<V> {
2856         ValueSpliterator(TreeMap<K,V> tree,
2857                          TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence,
2858                          int side, int est, int expectedModCount) {
2859             super(tree, origin, fence, side, est, expectedModCount);
2860         }
2861 
2862         public ValueSpliterator<K,V> trySplit() {
2863             if (est < 0)
2864                 getEstimate(); // force initialization
2865             int d = side;
2866             TreeMap.Entry<K,V> e = current, f = fence,
2867                     s = ((e == null || e == f) ? null :      // empty
2868                          (d == 0)              ? tree.root : // was top
2869                          (d >  0)              ? e.right :   // was right
2870                          (d <  0 && f != null) ? f.left :    // was left
2871                          null);
2872             if (s != null && s != e && s != f &&
2873                 tree.compare(e.key, s.key) < 0) {        // e not already past s
2874                 side = 1;
2875                 return new ValueSpliterator<>
2876                         (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2877             }
2878             return null;
2879         }
2880 
2881         public void forEachRemaining(Consumer<? super V> action) {
2882             if (action == null)
2883                 throw new NullPointerException();
2884             if (est < 0)
2885                 getEstimate(); // force initialization
2886             TreeMap.Entry<K,V> f = fence, e, p, pl;
2887             if ((e = current) != null && e != f) {
2888                 current = f; // exhaust
2889                 do {
2890                     action.accept(e.value);
2891                     if ((p = e.right) != null) {
2892                         while ((pl = p.left) != null)
2893                             p = pl;
2894                     }
2895                     else {
2896                         while ((p = e.parent) != null && e == p.right)
2897                             e = p;
2898                     }
2899                 } while ((e = p) != null && e != f);
2900                 if (tree.modCount != expectedModCount)
2901                     throw new ConcurrentModificationException();
2902             }
2903         }
2904 
2905         public boolean tryAdvance(Consumer<? super V> action) {
2906             TreeMap.Entry<K,V> e;
2907             if (action == null)
2908                 throw new NullPointerException();
2909             if (est < 0)
2910                 getEstimate(); // force initialization
2911             if ((e = current) == null || e == fence)
2912                 return false;
2913             current = successor(e);
2914             action.accept(e.value);
2915             if (tree.modCount != expectedModCount)
2916                 throw new ConcurrentModificationException();
2917             return true;
2918         }
2919 
2920         public int characteristics() {
2921             return (side == 0 ? Spliterator.SIZED : 0) | Spliterator.ORDERED;
2922         }
2923     }
2924 
2925     static final class EntrySpliterator<K,V>
2926         extends TreeMapSpliterator<K,V>
2927         implements Spliterator<Map.Entry<K,V>> {
2928         EntrySpliterator(TreeMap<K,V> tree,
2929                          TreeMap.Entry<K,V> origin, TreeMap.Entry<K,V> fence,
2930                          int side, int est, int expectedModCount) {
2931             super(tree, origin, fence, side, est, expectedModCount);
2932         }
2933 
2934         public EntrySpliterator<K,V> trySplit() {
2935             if (est < 0)
2936                 getEstimate(); // force initialization
2937             int d = side;
2938             TreeMap.Entry<K,V> e = current, f = fence,
2939                     s = ((e == null || e == f) ? null :      // empty
2940                          (d == 0)              ? tree.root : // was top
2941                          (d >  0)              ? e.right :   // was right
2942                          (d <  0 && f != null) ? f.left :    // was left
2943                          null);
2944             if (s != null && s != e && s != f &&
2945                 tree.compare(e.key, s.key) < 0) {        // e not already past s
2946                 side = 1;
2947                 return new EntrySpliterator<>
2948                         (tree, e, current = s, -1, est >>>= 1, expectedModCount);
2949             }
2950             return null;
2951         }
2952 
2953         public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
2954             if (action == null)
2955                 throw new NullPointerException();
2956             if (est < 0)
2957                 getEstimate(); // force initialization
2958             TreeMap.Entry<K,V> f = fence, e, p, pl;
2959             if ((e = current) != null && e != f) {
2960                 current = f; // exhaust
2961                 do {
2962                     action.accept(e);
2963                     if ((p = e.right) != null) {
2964                         while ((pl = p.left) != null)
2965                             p = pl;
2966                     }
2967                     else {
2968                         while ((p = e.parent) != null && e == p.right)
2969                             e = p;
2970                     }
2971                 } while ((e = p) != null && e != f);
2972                 if (tree.modCount != expectedModCount)
2973                     throw new ConcurrentModificationException();
2974             }
2975         }
2976 
2977         public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
2978             TreeMap.Entry<K,V> e;
2979             if (action == null)
2980                 throw new NullPointerException();
2981             if (est < 0)
2982                 getEstimate(); // force initialization
2983             if ((e = current) == null || e == fence)
2984                 return false;
2985             current = successor(e);
2986             action.accept(e);
2987             if (tree.modCount != expectedModCount)
2988                 throw new ConcurrentModificationException();
2989             return true;
2990         }
2991 
2992         public int characteristics() {
2993             return (side == 0 ? Spliterator.SIZED : 0) |
2994                     Spliterator.DISTINCT | Spliterator.SORTED | Spliterator.ORDERED;
2995         }
2996 
2997         @Override
2998         public Comparator<Map.Entry<K, V>> getComparator() {
2999             // Adapt or create a key-based comparator
3000             if (tree.comparator != null) {
3001                 return Map.Entry.comparingByKey(tree.comparator);
3002             }
3003             else {
3004                 return (Comparator<Map.Entry<K, V>> & Serializable) (e1, e2) -> {
3005                     @SuppressWarnings("unchecked")
3006                     Comparable<? super K> k1 = (Comparable<? super K>) e1.getKey();
3007                     return k1.compareTo(e2.getKey());
3008                 };
3009             }
3010         }
3011     }
3012 }