ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeMap.java
(Generate patch)

Comparing jsr166/src/main/java/util/TreeMap.java (file contents):
Revision 1.17 by dl, Thu May 26 12:07:07 2005 UTC vs.
Revision 1.37 by dl, Tue May 9 18:17:08 2006 UTC

# Line 1 | Line 1
1   /*
2   * %W% %E%
3   *
4 < * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
4 > * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5   * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6   */
7  
# Line 30 | Line 30 | package java.util;
30   * <i>is</i> well-defined even if its ordering is inconsistent with equals; it
31   * just fails to obey the general contract of the <tt>Map</tt> interface.
32   *
33 < * <p><b>Note that this implementation is not synchronized.</b> If multiple
34 < * threads access a map concurrently, and at least one of the threads modifies
35 < * the map structurally, it <i>must</i> be synchronized externally.  (A
36 < * structural modification is any operation that adds or deletes one or more
37 < * mappings; merely changing the value associated with an existing key is not
38 < * a structural modification.)  This is typically accomplished by
39 < * synchronizing on some object that naturally encapsulates the map.  If no
40 < * such object exists, the map should be "wrapped" using the
41 < * <tt>Collections.synchronizedMap</tt> method.  This is best done at creation
42 < * time, to prevent accidental unsynchronized access to the map:
43 < * <pre>
44 < *     Map m = Collections.synchronizedMap(new TreeMap(...));
45 < * </pre>
33 > * <p><strong>Note that this implementation is not synchronized.</strong>
34 > * If multiple threads access a map concurrently, and at least one of the
35 > * threads modifies the map structurally, it <i>must</i> be synchronized
36 > * externally.  (A structural modification is any operation that adds or
37 > * deletes one or more mappings; merely changing the value associated
38 > * with an existing key is not a structural modification.)  This is
39 > * typically accomplished by synchronizing on some object that naturally
40 > * encapsulates the map.
41 > * If no such object exists, the map should be "wrapped" using the
42 > * {@link Collections#synchronizedSortedMap Collections.synchronizedSortedMap}
43 > * method.  This is best done at creation time, to prevent accidental
44 > * unsynchronized access to the map: <pre>
45 > *   SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));</pre>
46   *
47   * <p>The iterators returned by the <tt>iterator</tt> method of the collections
48   * returned by all of this class's "collection view methods" are
# Line 68 | Line 68 | package java.util;
68   * associated map using <tt>put</tt>.)
69   *
70   * <p>This class is a member of the
71 < * <a href="{@docRoot}/../guide/collections/index.html">
71 > * <a href="{@docRoot}/../technotes/guides/collections/index.html">
72   * Java Collections Framework</a>.
73   *
74   * @param <K> the type of keys maintained by this map
# Line 82 | Line 82 | package java.util;
82   * @see Comparable
83   * @see Comparator
84   * @see Collection
85 * @see Collections#synchronizedMap(Map)
85   * @since 1.2
86   */
87  
# Line 96 | Line 95 | public class TreeMap<K,V>
95       *
96       * @serial
97       */
98 <    private Comparator<? super K> comparator = null;
98 >    private final Comparator<? super K> comparator;
99  
100      private transient Entry<K,V> root = null;
101  
# Line 110 | Line 109 | public class TreeMap<K,V>
109       */
110      private transient int modCount = 0;
111  
113    private void incrementSize()   { modCount++; size++; }
114    private void decrementSize()   { modCount++; size--; }
115
112      /**
113       * Constructs a new, empty tree map, using the natural ordering of its
114       * keys.  All keys inserted into the map must implement the {@link
# Line 126 | Line 122 | public class TreeMap<K,V>
122       * <tt>ClassCastException</tt>.
123       */
124      public TreeMap() {
125 +        comparator = null;
126      }
127  
128      /**
# Line 161 | Line 158 | public class TreeMap<K,V>
158       * @throws NullPointerException if the specified map is null
159       */
160      public TreeMap(Map<? extends K, ? extends V> m) {
161 +        comparator = null;
162          putAll(m);
163      }
164  
# Line 216 | Line 214 | public class TreeMap<K,V>
214       * specified value.  More formally, returns <tt>true</tt> if and only if
215       * this map contains at least one mapping to a value <tt>v</tt> such
216       * that <tt>(value==null ? v==null : value.equals(v))</tt>.  This
217 <     * operation requires time linear in the map size.
217 >     * operation will probably require time linear in the map size for
218 >     * most implementations.
219       *
220       * @param value value whose presence in this map is to be tested
221       * @return <tt>true</tt> if a mapping to <tt>value</tt> exists;
# Line 224 | Line 223 | public class TreeMap<K,V>
223       * @since 1.2
224       */
225      public boolean containsValue(Object value) {
226 <        return (root==null ? false :
227 <                (value==null ? valueSearchNull(root)
228 <                             : valueSearchNonNull(root, value)));
229 <    }
231 <
232 <    private boolean valueSearchNull(Entry n) {
233 <        if (n.value == null)
234 <            return true;
235 <
236 <        // Check left and right subtrees for value
237 <        return (n.left  != null && valueSearchNull(n.left)) ||
238 <               (n.right != null && valueSearchNull(n.right));
239 <    }
240 <
241 <    private boolean valueSearchNonNull(Entry n, Object value) {
242 <        // Check this node for the value
243 <        if (value.equals(n.value))
244 <            return true;
245 <
246 <        // Check left and right subtrees for value
247 <        return (n.left  != null && valueSearchNonNull(n.left, value)) ||
248 <               (n.right != null && valueSearchNonNull(n.right, value));
226 >        for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
227 >            if (valEquals(value, e.value))
228 >                return true;
229 >        return false;
230      }
231  
232      /**
233 <     * Returns the value to which this map maps the specified key, or
234 <     * <tt>null</tt> if the map contains no mapping for the key.  A return
235 <     * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
236 <     * map contains no mapping for the key; it's also possible that the map
237 <     * explicitly maps the key to <tt>null</tt>.  The {@link #containsKey}
238 <     * operation may be used to distinguish these two cases.
233 >     * Returns the value to which the specified key is mapped,
234 >     * or {@code null} if this map contains no mapping for the key.
235 >     *
236 >     * <p>More formally, if this map contains a mapping from a key
237 >     * {@code k} to a value {@code v} such that {@code key} compares
238 >     * equal to {@code k} according to the map's ordering, then this
239 >     * method returns {@code v}; otherwise it returns {@code null}.
240 >     * (There can be at most one such mapping.)
241 >     *
242 >     * <p>A return value of {@code null} does not <i>necessarily</i>
243 >     * indicate that the map contains no mapping for the key; it's also
244 >     * possible that the map explicitly maps the key to {@code null}.
245 >     * The {@link #containsKey containsKey} operation may be used to
246 >     * distinguish these two cases.
247       *
259     * @param key key whose associated value is to be returned
260     * @return the value to which this map maps the specified key, or
261     *         <tt>null</tt> if the map contains no mapping for the key
248       * @throws ClassCastException if the specified key cannot be compared
249       *         with the keys currently in the map
250       * @throws NullPointerException if the specified key is null
# Line 330 | Line 316 | public class TreeMap<K,V>
316       *         and this map uses natural ordering, or its comparator
317       *         does not permit null keys
318       */
319 <    private Entry<K,V> getEntry(Object key) {
319 >    final Entry<K,V> getEntry(Object key) {
320          // Offload comparator-based version for sake of performance
321          if (comparator != null)
322              return getEntryUsingComparator(key);
323 +        if (key == null)
324 +            throw new NullPointerException();
325          Comparable<? super K> k = (Comparable<? super K>) key;
326          Entry<K,V> p = root;
327          while (p != null) {
# Line 354 | Line 342 | public class TreeMap<K,V>
342       * that are less dependent on comparator performance, but is
343       * worthwhile here.)
344       */
345 <    private Entry<K,V> getEntryUsingComparator(Object key) {
345 >    final Entry<K,V> getEntryUsingComparator(Object key) {
346          K k = (K) key;
347          Comparator<? super K> cpr = comparator;
348 <        Entry<K,V> p = root;
349 <        while (p != null) {
350 <            int cmp = cpr.compare(k, p.key);
351 <            if (cmp < 0)
352 <                p = p.left;
353 <            else if (cmp > 0)
354 <                p = p.right;
355 <            else
356 <                return p;
348 >        if (cpr != null) {
349 >            Entry<K,V> p = root;
350 >            while (p != null) {
351 >                int cmp = cpr.compare(k, p.key);
352 >                if (cmp < 0)
353 >                    p = p.left;
354 >                else if (cmp > 0)
355 >                    p = p.right;
356 >                else
357 >                    return p;
358 >            }
359          }
360          return null;
361      }
# Line 376 | Line 366 | public class TreeMap<K,V>
366       * key; if no such entry exists (i.e., the greatest key in the Tree is less
367       * than the specified key), returns <tt>null</tt>.
368       */
369 <    private Entry<K,V> getCeilingEntry(K key) {
369 >    final Entry<K,V> getCeilingEntry(K key) {
370          Entry<K,V> p = root;
371 <        if (p==null)
382 <            return null;
383 <
384 <        while (true) {
371 >        while (p != null) {
372              int cmp = compare(key, p.key);
373              if (cmp < 0) {
374                  if (p.left != null)
# Line 403 | Line 390 | public class TreeMap<K,V>
390              } else
391                  return p;
392          }
393 +        return null;
394      }
395  
396      /**
# Line 410 | Line 398 | public class TreeMap<K,V>
398       * exists, returns the entry for the greatest key less than the specified
399       * key; if no such entry exists, returns <tt>null</tt>.
400       */
401 <    private Entry<K,V> getFloorEntry(K key) {
401 >    final Entry<K,V> getFloorEntry(K key) {
402          Entry<K,V> p = root;
403 <        if (p==null)
416 <            return null;
417 <
418 <        while (true) {
403 >        while (p != null) {
404              int cmp = compare(key, p.key);
405              if (cmp > 0) {
406                  if (p.right != null)
# Line 438 | Line 423 | public class TreeMap<K,V>
423                  return p;
424  
425          }
426 +        return null;
427      }
428  
429      /**
# Line 446 | Line 432 | public class TreeMap<K,V>
432       * key greater than the specified key; if no such entry exists
433       * returns <tt>null</tt>.
434       */
435 <    private Entry<K,V> getHigherEntry(K key) {
435 >    final Entry<K,V> getHigherEntry(K key) {
436          Entry<K,V> p = root;
437 <        if (p==null)
452 <            return null;
453 <
454 <        while (true) {
437 >        while (p != null) {
438              int cmp = compare(key, p.key);
439              if (cmp < 0) {
440                  if (p.left != null)
# Line 472 | Line 455 | public class TreeMap<K,V>
455                  }
456              }
457          }
458 +        return null;
459      }
460  
461      /**
# Line 479 | Line 463 | public class TreeMap<K,V>
463       * no such entry exists (i.e., the least key in the Tree is greater than
464       * the specified key), returns <tt>null</tt>.
465       */
466 <    private Entry<K,V> getLowerEntry(K key) {
466 >    final Entry<K,V> getLowerEntry(K key) {
467          Entry<K,V> p = root;
468 <        if (p==null)
485 <            return null;
486 <
487 <        while (true) {
468 >        while (p != null) {
469              int cmp = compare(key, p.key);
470              if (cmp > 0) {
471                  if (p.right != null)
# Line 505 | Line 486 | public class TreeMap<K,V>
486                  }
487              }
488          }
489 <    }
509 <
510 <    /**
511 <     * Returns the key corresponding to the specified Entry.
512 <     * @throws NoSuchElementException if the Entry is null
513 <     */
514 <    private static <K> K key(Entry<K,?> e) {
515 <        if (e==null)
516 <            throw new NoSuchElementException();
517 <        return e.key;
489 >        return null;
490      }
491  
492      /**
493       * Associates the specified value with the specified key in this map.
494 <     * If the map previously contained a mapping for this key, the old
494 >     * If the map previously contained a mapping for the key, the old
495       * value is replaced.
496       *
497       * @param key key with which the specified value is to be associated
# Line 537 | Line 509 | public class TreeMap<K,V>
509       */
510      public V put(K key, V value) {
511          Entry<K,V> t = root;
540
512          if (t == null) {
513 <            if (key == null) {
514 <                if (comparator == null)
515 <                    throw new NullPointerException();
516 <                comparator.compare(key, key);
517 <            }
547 <            incrementSize();
513 >            // TBD:
514 >            // 5045147: (coll) Adding null to an empty TreeSet should
515 >            // throw NullPointerException
516 >            //
517 >            // compare(key, key); // type check
518              root = new Entry<K,V>(key, value, null);
519 +            size = 1;
520 +            modCount++;
521              return null;
522          }
523 <
524 <        while (true) {
525 <            int cmp = compare(key, t.key);
526 <            if (cmp == 0) {
527 <                return t.setValue(value);
528 <            } else if (cmp < 0) {
529 <                if (t.left != null) {
523 >        int cmp;
524 >        Entry<K,V> parent;
525 >        // split comparator and comparable paths
526 >        Comparator<? super K> cpr = comparator;
527 >        if (cpr != null) {
528 >            do {
529 >                parent = t;
530 >                cmp = cpr.compare(key, t.key);
531 >                if (cmp < 0)
532                      t = t.left;
533 <                } else {
560 <                    incrementSize();
561 <                    t.left = new Entry<K,V>(key, value, t);
562 <                    fixAfterInsertion(t.left);
563 <                    return null;
564 <                }
565 <            } else { // cmp > 0
566 <                if (t.right != null) {
533 >                else if (cmp > 0)
534                      t = t.right;
535 <                } else {
536 <                    incrementSize();
537 <                    t.right = new Entry<K,V>(key, value, t);
571 <                    fixAfterInsertion(t.right);
572 <                    return null;
573 <                }
574 <            }
535 >                else
536 >                    return t.setValue(value);
537 >            } while (t != null);
538          }
539 +        else {
540 +            if (key == null)
541 +                throw new NullPointerException();
542 +            Comparable<? super K> k = (Comparable<? super K>) key;
543 +            do {
544 +                parent = t;
545 +                cmp = k.compareTo(t.key);
546 +                if (cmp < 0)
547 +                    t = t.left;
548 +                else if (cmp > 0)
549 +                    t = t.right;
550 +                else
551 +                    return t.setValue(value);
552 +            } while (t != null);
553 +        }
554 +        Entry<K,V> e = new Entry<K,V>(key, value, parent);
555 +        if (cmp < 0)
556 +            parent.left = e;
557 +        else
558 +            parent.right = e;
559 +        fixAfterInsertion(e);
560 +        size++;
561 +        modCount++;
562 +        return null;
563      }
564  
565      /**
# Line 628 | Line 615 | public class TreeMap<K,V>
615          clone.size = 0;
616          clone.modCount = 0;
617          clone.entrySet = null;
618 <        clone.descendingEntrySet = null;
619 <        clone.descendingKeySet = null;
618 >        clone.navigableKeySet = null;
619 >        clone.descendingMap = null;
620  
621          // Initialize clone with our mappings
622          try {
# Line 643 | Line 630 | public class TreeMap<K,V>
630  
631      // NavigableMap API methods
632  
633 +    /**
634 +     * @since 1.6
635 +     */
636      public Map.Entry<K,V> firstEntry() {
637 <        Entry<K,V> e = getFirstEntry();
648 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
637 >        return exportEntry(getFirstEntry());
638      }
639  
640 +    /**
641 +     * @since 1.6
642 +     */
643      public Map.Entry<K,V> lastEntry() {
644 <        Entry<K,V> e = getLastEntry();
653 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
644 >        return exportEntry(getLastEntry());
645      }
646  
647 +    /**
648 +     * @since 1.6
649 +     */
650      public Map.Entry<K,V> pollFirstEntry() {
651          Entry<K,V> p = getFirstEntry();
652 <        if (p == null)
653 <            return null;
654 <        Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(p);
661 <        deleteEntry(p);
652 >        Map.Entry<K,V> result = exportEntry(p);
653 >        if (p != null)
654 >            deleteEntry(p);
655          return result;
656      }
657  
658 +    /**
659 +     * @since 1.6
660 +     */
661      public Map.Entry<K,V> pollLastEntry() {
662          Entry<K,V> p = getLastEntry();
663 <        if (p == null)
664 <            return null;
665 <        Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(p);
670 <        deleteEntry(p);
663 >        Map.Entry<K,V> result = exportEntry(p);
664 >        if (p != null)
665 >            deleteEntry(p);
666          return result;
667      }
668  
# Line 676 | Line 671 | public class TreeMap<K,V>
671       * @throws NullPointerException if the specified key is null
672       *         and this map uses natural ordering, or its comparator
673       *         does not permit null keys
674 +     * @since 1.6
675       */
676      public Map.Entry<K,V> lowerEntry(K key) {
677 <        Entry<K,V> e =  getLowerEntry(key);
682 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
677 >        return exportEntry(getLowerEntry(key));
678      }
679  
680      /**
# Line 687 | Line 682 | public class TreeMap<K,V>
682       * @throws NullPointerException if the specified key is null
683       *         and this map uses natural ordering, or its comparator
684       *         does not permit null keys
685 +     * @since 1.6
686       */
687      public K lowerKey(K key) {
688 <        Entry<K,V> e =  getLowerEntry(key);
693 <        return (e == null)? null : e.key;
688 >        return keyOrNull(getLowerEntry(key));
689      }
690  
691      /**
# Line 698 | Line 693 | public class TreeMap<K,V>
693       * @throws NullPointerException if the specified key is null
694       *         and this map uses natural ordering, or its comparator
695       *         does not permit null keys
696 +     * @since 1.6
697       */
698      public Map.Entry<K,V> floorEntry(K key) {
699 <        Entry<K,V> e = getFloorEntry(key);
704 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
699 >        return exportEntry(getFloorEntry(key));
700      }
701  
702      /**
# Line 709 | Line 704 | public class TreeMap<K,V>
704       * @throws NullPointerException if the specified key is null
705       *         and this map uses natural ordering, or its comparator
706       *         does not permit null keys
707 +     * @since 1.6
708       */
709      public K floorKey(K key) {
710 <        Entry<K,V> e = getFloorEntry(key);
715 <        return (e == null)? null : e.key;
710 >        return keyOrNull(getFloorEntry(key));
711      }
712  
713      /**
# Line 720 | Line 715 | public class TreeMap<K,V>
715       * @throws NullPointerException if the specified key is null
716       *         and this map uses natural ordering, or its comparator
717       *         does not permit null keys
718 +     * @since 1.6
719       */
720      public Map.Entry<K,V> ceilingEntry(K key) {
721 <        Entry<K,V> e = getCeilingEntry(key);
726 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
721 >        return exportEntry(getCeilingEntry(key));
722      }
723  
724      /**
# Line 731 | Line 726 | public class TreeMap<K,V>
726       * @throws NullPointerException if the specified key is null
727       *         and this map uses natural ordering, or its comparator
728       *         does not permit null keys
729 +     * @since 1.6
730       */
731      public K ceilingKey(K key) {
732 <        Entry<K,V> e = getCeilingEntry(key);
737 <        return (e == null)? null : e.key;
732 >        return keyOrNull(getCeilingEntry(key));
733      }
734  
735      /**
# Line 742 | Line 737 | public class TreeMap<K,V>
737       * @throws NullPointerException if the specified key is null
738       *         and this map uses natural ordering, or its comparator
739       *         does not permit null keys
740 +     * @since 1.6
741       */
742      public Map.Entry<K,V> higherEntry(K key) {
743 <        Entry<K,V> e = getHigherEntry(key);
748 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
743 >        return exportEntry(getHigherEntry(key));
744      }
745  
746      /**
# Line 753 | Line 748 | public class TreeMap<K,V>
748       * @throws NullPointerException if the specified key is null
749       *         and this map uses natural ordering, or its comparator
750       *         does not permit null keys
751 +     * @since 1.6
752       */
753      public K higherKey(K key) {
754 <        Entry<K,V> e = getHigherEntry(key);
759 <        return (e == null)? null : e.key;
754 >        return keyOrNull(getHigherEntry(key));
755      }
756  
757      // Views
# Line 766 | Line 761 | public class TreeMap<K,V>
761       * the first time this view is requested.  Views are stateless, so
762       * there's no reason to create more than one.
763       */
764 <    private transient Set<Map.Entry<K,V>> entrySet = null;
765 <    private transient Set<Map.Entry<K,V>> descendingEntrySet = null;
766 <    private transient Set<K> descendingKeySet = null;
764 >    private transient EntrySet entrySet = null;
765 >    private transient KeySet<K> navigableKeySet = null;
766 >    private transient NavigableMap<K,V> descendingMap = null;
767  
768      /**
769       * Returns a {@link Set} view of the keys contained in this map.
# Line 785 | Line 780 | public class TreeMap<K,V>
780       * operations.
781       */
782      public Set<K> keySet() {
783 <        Set<K> ks = keySet;
789 <        return (ks != null) ? ks : (keySet = new KeySet());
783 >        return navigableKeySet();
784      }
785  
786 <    class KeySet extends AbstractSet<K> {
787 <        public Iterator<K> iterator() {
788 <            return new KeyIterator(getFirstEntry());
789 <        }
790 <
791 <        public int size() {
792 <            return TreeMap.this.size();
799 <        }
800 <
801 <        public boolean contains(Object o) {
802 <            return containsKey(o);
803 <        }
804 <
805 <        public boolean remove(Object o) {
806 <            int oldSize = size;
807 <            TreeMap.this.remove(o);
808 <            return size != oldSize;
809 <        }
786 >    /**
787 >     * @since 1.6
788 >     */
789 >    public NavigableSet<K> navigableKeySet() {
790 >        KeySet<K> nks = navigableKeySet;
791 >        return (nks != null) ? nks : (navigableKeySet = new KeySet(this));
792 >    }
793  
794 <        public void clear() {
795 <            TreeMap.this.clear();
796 <        }
794 >    /**
795 >     * @since 1.6
796 >     */
797 >    public NavigableSet<K> descendingKeySet() {
798 >        return descendingMap().navigableKeySet();
799      }
800  
801      /**
# Line 833 | Line 818 | public class TreeMap<K,V>
818          return (vs != null) ? vs : (values = new Values());
819      }
820  
821 +    /**
822 +     * Returns a {@link Set} view of the mappings contained in this map.
823 +     * The set's iterator returns the entries in ascending key order.
824 +     * The set is backed by the map, so changes to the map are
825 +     * reflected in the set, and vice-versa.  If the map is modified
826 +     * while an iteration over the set is in progress (except through
827 +     * the iterator's own <tt>remove</tt> operation, or through the
828 +     * <tt>setValue</tt> operation on a map entry returned by the
829 +     * iterator) the results of the iteration are undefined.  The set
830 +     * supports element removal, which removes the corresponding
831 +     * mapping from the map, via the <tt>Iterator.remove</tt>,
832 +     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
833 +     * <tt>clear</tt> operations.  It does not support the
834 +     * <tt>add</tt> or <tt>addAll</tt> operations.
835 +     */
836 +    public Set<Map.Entry<K,V>> entrySet() {
837 +        EntrySet es = entrySet;
838 +        return (es != null) ? es : (entrySet = new EntrySet());
839 +    }
840 +
841 +    /**
842 +     * @since 1.6
843 +     */
844 +    public NavigableMap<K, V> descendingMap() {
845 +        NavigableMap<K, V> km = descendingMap;
846 +        return (km != null) ? km :
847 +            (descendingMap = new DescendingSubMap(this,
848 +                                                  true, null, true,
849 +                                                  true, null, true));
850 +    }
851 +
852 +    /**
853 +     * @throws ClassCastException       {@inheritDoc}
854 +     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
855 +     *         null and this map uses natural ordering, or its comparator
856 +     *         does not permit null keys
857 +     * @throws IllegalArgumentException {@inheritDoc}
858 +     * @since 1.6
859 +     */
860 +    public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
861 +                                    K toKey,   boolean toInclusive) {
862 +        return new AscendingSubMap(this,
863 +                                   false, fromKey, fromInclusive,
864 +                                   false, toKey,   toInclusive);
865 +    }
866 +
867 +    /**
868 +     * @throws ClassCastException       {@inheritDoc}
869 +     * @throws NullPointerException if <tt>toKey</tt> is null
870 +     *         and this map uses natural ordering, or its comparator
871 +     *         does not permit null keys
872 +     * @throws IllegalArgumentException {@inheritDoc}
873 +     * @since 1.6
874 +     */
875 +    public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
876 +        return new AscendingSubMap(this,
877 +                                   true,  null,  true,
878 +                                   false, toKey, inclusive);
879 +    }
880 +
881 +    /**
882 +     * @throws ClassCastException       {@inheritDoc}
883 +     * @throws NullPointerException if <tt>fromKey</tt> is null
884 +     *         and this map uses natural ordering, or its comparator
885 +     *         does not permit null keys
886 +     * @throws IllegalArgumentException {@inheritDoc}
887 +     * @since 1.6
888 +     */
889 +    public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
890 +        return new AscendingSubMap(this,
891 +                                   false, fromKey, inclusive,
892 +                                   true,  null,    true);
893 +    }
894 +
895 +    /**
896 +     * @throws ClassCastException       {@inheritDoc}
897 +     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
898 +     *         null and this map uses natural ordering, or its comparator
899 +     *         does not permit null keys
900 +     * @throws IllegalArgumentException {@inheritDoc}
901 +     */
902 +    public SortedMap<K,V> subMap(K fromKey, K toKey) {
903 +        return subMap(fromKey, true, toKey, false);
904 +    }
905 +
906 +    /**
907 +     * @throws ClassCastException       {@inheritDoc}
908 +     * @throws NullPointerException if <tt>toKey</tt> is null
909 +     *         and this map uses natural ordering, or its comparator
910 +     *         does not permit null keys
911 +     * @throws IllegalArgumentException {@inheritDoc}
912 +     */
913 +    public SortedMap<K,V> headMap(K toKey) {
914 +        return headMap(toKey, false);
915 +    }
916 +
917 +    /**
918 +     * @throws ClassCastException       {@inheritDoc}
919 +     * @throws NullPointerException if <tt>fromKey</tt> is null
920 +     *         and this map uses natural ordering, or its comparator
921 +     *         does not permit null keys
922 +     * @throws IllegalArgumentException {@inheritDoc}
923 +     */
924 +    public SortedMap<K,V> tailMap(K fromKey) {
925 +        return tailMap(fromKey, true);
926 +    }
927 +
928 +    // View class support
929 +
930      class Values extends AbstractCollection<V> {
931          public Iterator<V> iterator() {
932              return new ValueIterator(getFirstEntry());
# Line 843 | Line 937 | public class TreeMap<K,V>
937          }
938  
939          public boolean contains(Object o) {
940 <            for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
847 <                if (valEquals(e.getValue(), o))
848 <                    return true;
849 <            return false;
940 >            return TreeMap.this.containsValue(o);
941          }
942  
943          public boolean remove(Object o) {
# Line 864 | Line 955 | public class TreeMap<K,V>
955          }
956      }
957  
867    /**
868     * Returns a {@link Set} view of the mappings contained in this map.
869     * The set's iterator returns the entries in ascending key order.
870     * The set is backed by the map, so changes to the map are
871     * reflected in the set, and vice-versa.  If the map is modified
872     * while an iteration over the set is in progress (except through
873     * the iterator's own <tt>remove</tt> operation, or through the
874     * <tt>setValue</tt> operation on a map entry returned by the
875     * iterator) the results of the iteration are undefined.  The set
876     * supports element removal, which removes the corresponding
877     * mapping from the map, via the <tt>Iterator.remove</tt>,
878     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
879     * <tt>clear</tt> operations.  It does not support the
880     * <tt>add</tt> or <tt>addAll</tt> operations.
881     */
882    public Set<Map.Entry<K,V>> entrySet() {
883        Set<Map.Entry<K,V>> es = entrySet;
884        return (es != null) ? es : (entrySet = new EntrySet());
885    }
886
958      class EntrySet extends AbstractSet<Map.Entry<K,V>> {
959          public Iterator<Map.Entry<K,V>> iterator() {
960              return new EntryIterator(getFirstEntry());
# Line 920 | Line 991 | public class TreeMap<K,V>
991          }
992      }
993  
994 <    public Set<Map.Entry<K,V>> descendingEntrySet() {
995 <        Set<Map.Entry<K,V>> es = descendingEntrySet;
996 <        return (es != null) ? es : (descendingEntrySet = new DescendingEntrySet());
997 <    }
994 >    /*
995 >     * Unlike Values and EntrySet, the KeySet class is static,
996 >     * delegating to a NavigableMap to allow use by SubMaps, which
997 >     * outweighs the ugliness of needing type-tests for the following
998 >     * Iterator methods that are defined appropriately in main versus
999 >     * submap classes.
1000 >     */
1001  
1002 <    class DescendingEntrySet extends EntrySet {
1003 <        public Iterator<Map.Entry<K,V>> iterator() {
930 <            return new DescendingEntryIterator(getLastEntry());
931 <        }
1002 >    Iterator<K> keyIterator() {
1003 >        return new KeyIterator(getFirstEntry());
1004      }
1005  
1006 <    public Set<K> descendingKeySet() {
1007 <        Set<K> ks = descendingKeySet;
936 <        return (ks != null) ? ks : (descendingKeySet = new DescendingKeySet());
1006 >    Iterator<K> descendingKeyIterator() {
1007 >        return new DescendingKeyIterator(getFirstEntry());
1008      }
1009  
1010 <    class DescendingKeySet extends KeySet {
1011 <        public Iterator<K> iterator() {
1012 <            return new DescendingKeyIterator(getLastEntry());
1010 >    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
1011 >        private final NavigableMap<E, Object> m;
1012 >        KeySet(NavigableMap<E,Object> map) { m = map; }
1013 >
1014 >        public Iterator<E> iterator() {
1015 >            if (m instanceof TreeMap)
1016 >                return ((TreeMap<E,Object>)m).keyIterator();
1017 >            else
1018 >                return (Iterator<E>)(((TreeMap.NavigableSubMap)m).keyIterator());
1019 >        }
1020 >
1021 >        public Iterator<E> descendingIterator() {
1022 >            if (m instanceof TreeMap)
1023 >                return ((TreeMap<E,Object>)m).descendingKeyIterator();
1024 >            else
1025 >                return (Iterator<E>)(((TreeMap.NavigableSubMap)m).descendingKeyIterator());
1026 >        }
1027 >
1028 >        public int size() { return m.size(); }
1029 >        public boolean isEmpty() { return m.isEmpty(); }
1030 >        public boolean contains(Object o) { return m.containsKey(o); }
1031 >        public void clear() { m.clear(); }
1032 >        public E lower(E e) { return m.lowerKey(e); }
1033 >        public E floor(E e) { return m.floorKey(e); }
1034 >        public E ceiling(E e) { return m.ceilingKey(e); }
1035 >        public E higher(E e) { return m.higherKey(e); }
1036 >        public E first() { return m.firstKey(); }
1037 >        public E last() { return m.lastKey(); }
1038 >        public Comparator<? super E> comparator() { return m.comparator(); }
1039 >        public E pollFirst() {
1040 >            Map.Entry<E,Object> e = m.pollFirstEntry();
1041 >            return e == null? null : e.getKey();
1042 >        }
1043 >        public E pollLast() {
1044 >            Map.Entry<E,Object> e = m.pollLastEntry();
1045 >            return e == null? null : e.getKey();
1046 >        }
1047 >        public boolean remove(Object o) {
1048 >            int oldSize = size();
1049 >            m.remove(o);
1050 >            return size() != oldSize;
1051 >        }
1052 >        public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
1053 >                                      E toElement,   boolean toInclusive) {
1054 >            return new TreeSet<E>(m.subMap(fromElement, fromInclusive,
1055 >                                           toElement,   toInclusive));
1056 >        }
1057 >        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1058 >            return new TreeSet<E>(m.headMap(toElement, inclusive));
1059 >        }
1060 >        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1061 >            return new TreeSet<E>(m.tailMap(fromElement, inclusive));
1062 >        }
1063 >        public SortedSet<E> subSet(E fromElement, E toElement) {
1064 >            return subSet(fromElement, true, toElement, false);
1065 >        }
1066 >        public SortedSet<E> headSet(E toElement) {
1067 >            return headSet(toElement, false);
1068 >        }
1069 >        public SortedSet<E> tailSet(E fromElement) {
1070 >            return tailSet(fromElement, true);
1071 >        }
1072 >        public NavigableSet<E> descendingSet() {
1073 >            return new TreeSet(m.descendingMap());
1074          }
1075      }
1076  
1077      /**
1078 <     * @throws ClassCastException       {@inheritDoc}
947 <     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
948 <     *         null and this map uses natural ordering, or its comparator
949 <     *         does not permit null keys
950 <     * @throws IllegalArgumentException {@inheritDoc}
1078 >     * Base class for TreeMap Iterators
1079       */
1080 <    public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1081 <        return new SubMap(fromKey, toKey);
1080 >    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1081 >        Entry<K,V> next;
1082 >        Entry<K,V> lastReturned;
1083 >        int expectedModCount;
1084 >
1085 >        PrivateEntryIterator(Entry<K,V> first) {
1086 >            expectedModCount = modCount;
1087 >            lastReturned = null;
1088 >            next = first;
1089 >        }
1090 >
1091 >        public final boolean hasNext() {
1092 >            return next != null;
1093 >        }
1094 >
1095 >        final Entry<K,V> nextEntry() {
1096 >            Entry<K,V> e = lastReturned = next;
1097 >            if (e == null)
1098 >                throw new NoSuchElementException();
1099 >            if (modCount != expectedModCount)
1100 >                throw new ConcurrentModificationException();
1101 >            next = successor(e);
1102 >            return e;
1103 >        }
1104 >
1105 >        final Entry<K,V> prevEntry() {
1106 >            Entry<K,V> e = lastReturned= next;
1107 >            if (e == null)
1108 >                throw new NoSuchElementException();
1109 >            if (modCount != expectedModCount)
1110 >                throw new ConcurrentModificationException();
1111 >            next = predecessor(e);
1112 >            return e;
1113 >        }
1114 >
1115 >        public void remove() {
1116 >            if (lastReturned == null)
1117 >                throw new IllegalStateException();
1118 >            if (modCount != expectedModCount)
1119 >                throw new ConcurrentModificationException();
1120 >            // deleted entries are replaced by their successors
1121 >            if (lastReturned.left != null && lastReturned.right != null)
1122 >                next = lastReturned;
1123 >            deleteEntry(lastReturned);
1124 >            expectedModCount++;
1125 >            lastReturned = null;
1126 >        }
1127 >    }
1128 >
1129 >    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1130 >        EntryIterator(Entry<K,V> first) {
1131 >            super(first);
1132 >        }
1133 >        public Map.Entry<K,V> next() {
1134 >            return nextEntry();
1135 >        }
1136 >    }
1137 >
1138 >    final class ValueIterator extends PrivateEntryIterator<V> {
1139 >        ValueIterator(Entry<K,V> first) {
1140 >            super(first);
1141 >        }
1142 >        public V next() {
1143 >            return nextEntry().value;
1144 >        }
1145 >    }
1146 >
1147 >    final class KeyIterator extends PrivateEntryIterator<K> {
1148 >        KeyIterator(Entry<K,V> first) {
1149 >            super(first);
1150 >        }
1151 >        public K next() {
1152 >            return nextEntry().key;
1153 >        }
1154      }
1155  
1156 +    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1157 +        DescendingKeyIterator(Entry<K,V> first) {
1158 +            super(first);
1159 +        }
1160 +        public K next() {
1161 +            return prevEntry().key;
1162 +        }
1163 +    }
1164 +
1165 +    // Little utilities
1166 +
1167      /**
1168 <     * @throws ClassCastException       {@inheritDoc}
958 <     * @throws NullPointerException if <tt>toKey</tt> is null
959 <     *         and this map uses natural ordering, or its comparator
960 <     *         does not permit null keys
961 <     * @throws IllegalArgumentException {@inheritDoc}
1168 >     * Compares two keys using the correct comparison method for this TreeMap.
1169       */
1170 <    public NavigableMap<K,V> navigableHeadMap(K toKey) {
1171 <        return new SubMap(toKey, true);
1170 >    final int compare(Object k1, Object k2) {
1171 >        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1172 >            : comparator.compare((K)k1, (K)k2);
1173      }
1174  
1175      /**
1176 <     * @throws ClassCastException       {@inheritDoc}
1177 <     * @throws NullPointerException if <tt>fromKey</tt> is null
970 <     *         and this map uses natural ordering, or its comparator
971 <     *         does not permit null keys
972 <     * @throws IllegalArgumentException {@inheritDoc}
1176 >     * Test two values for equality.  Differs from o1.equals(o2) only in
1177 >     * that it copes with <tt>null</tt> o1 properly.
1178       */
1179 <    public NavigableMap<K,V> navigableTailMap(K fromKey) {
1180 <        return new SubMap(fromKey, false);
1179 >    final static boolean valEquals(Object o1, Object o2) {
1180 >        return (o1==null ? o2==null : o1.equals(o2));
1181      }
1182  
1183      /**
1184 <     * Equivalent to {@link #navigableSubMap} but with a return type
980 <     * conforming to the <tt>SortedMap</tt> interface.
981 <     *
982 <     * <p>{@inheritDoc}
983 <     *
984 <     * @throws ClassCastException       {@inheritDoc}
985 <     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
986 <     *         null and this map uses natural ordering, or its comparator
987 <     *         does not permit null keys
988 <     * @throws IllegalArgumentException {@inheritDoc}
1184 >     * Return SimpleImmutableEntry for entry, or null if null
1185       */
1186 <    public SortedMap<K,V> subMap(K fromKey, K toKey) {
1187 <        return new SubMap(fromKey, toKey);
1186 >    static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
1187 >        return e == null? null :
1188 >            new AbstractMap.SimpleImmutableEntry<K,V>(e);
1189      }
1190  
1191      /**
1192 <     * Equivalent to {@link #navigableHeadMap} but with a return type
996 <     * conforming to the <tt>SortedMap</tt> interface.
997 <     *
998 <     * <p>{@inheritDoc}
999 <     *
1000 <     * @throws ClassCastException       {@inheritDoc}
1001 <     * @throws NullPointerException if <tt>toKey</tt> is null
1002 <     *         and this map uses natural ordering, or its comparator
1003 <     *         does not permit null keys
1004 <     * @throws IllegalArgumentException {@inheritDoc}
1192 >     * Return key for entry, or null if null
1193       */
1194 <    public SortedMap<K,V> headMap(K toKey) {
1195 <        return new SubMap(toKey, true);
1194 >    static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
1195 >        return e == null? null : e.key;
1196      }
1197  
1198      /**
1199 <     * Equivalent to {@link #navigableTailMap} but with a return type
1200 <     * conforming to the <tt>SortedMap</tt> interface.
1013 <     *
1014 <     * <p>{@inheritDoc}
1015 <     *
1016 <     * @throws ClassCastException       {@inheritDoc}
1017 <     * @throws NullPointerException if <tt>fromKey</tt> is null
1018 <     *         and this map uses natural ordering, or its comparator
1019 <     *         does not permit null keys
1020 <     * @throws IllegalArgumentException {@inheritDoc}
1199 >     * Returns the key corresponding to the specified Entry.
1200 >     * @throws NoSuchElementException if the Entry is null
1201       */
1202 <    public SortedMap<K,V> tailMap(K fromKey) {
1203 <        return new SubMap(fromKey, false);
1202 >    static <K> K key(Entry<K,?> e) {
1203 >        if (e==null)
1204 >            throw new NoSuchElementException();
1205 >        return e.key;
1206      }
1207  
1026    private class SubMap
1027        extends AbstractMap<K,V>
1028        implements NavigableMap<K,V>, java.io.Serializable {
1029        private static final long serialVersionUID = -6520786458950516097L;
1208  
1209 +    // SubMaps
1210 +
1211 +    /**
1212 +     * @serial include
1213 +     */
1214 +    static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
1215 +        implements NavigableMap<K,V>, java.io.Serializable {
1216          /**
1217 <         * fromKey is significant only if fromStart is false.  Similarly,
1033 <         * toKey is significant only if toStart is false.
1217 >         * The backing map.
1218           */
1219 <        private boolean fromStart = false, toEnd = false;
1036 <        private K fromKey, toKey;
1219 >        final TreeMap<K,V> m;
1220  
1221 <        SubMap(K fromKey, K toKey) {
1222 <            if (compare(fromKey, toKey) > 0)
1223 <                throw new IllegalArgumentException("fromKey > toKey");
1224 <            this.fromKey = fromKey;
1225 <            this.toKey = toKey;
1226 <        }
1227 <
1228 <        SubMap(K key, boolean headMap) {
1229 <            compare(key, key); // Type-check key
1230 <
1231 <            if (headMap) {
1232 <                fromStart = true;
1233 <                toKey = key;
1221 >        /**
1222 >         * Endpoints are represented as triples (fromStart, lo,
1223 >         * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is
1224 >         * true, then the low (absolute) bound is the start of the
1225 >         * backing map, and the other values are ignored. Otherwise,
1226 >         * if loInclusive is true, lo is the inclusive bound, else lo
1227 >         * is the exclusive bound. Similarly for the upper bound.
1228 >         */
1229 >        final K lo, hi;
1230 >        final boolean fromStart, toEnd;
1231 >        final boolean loInclusive, hiInclusive;
1232 >
1233 >        NavigableSubMap(TreeMap<K,V> m,
1234 >                        boolean fromStart, K lo, boolean loInclusive,
1235 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1236 >            if (!fromStart && !toEnd) {
1237 >                if (m.compare(lo, hi) > 0)
1238 >                    throw new IllegalArgumentException("fromKey > toKey");
1239              } else {
1240 <                toEnd = true;
1241 <                fromKey = key;
1240 >                if (!fromStart) // type check
1241 >                    m.compare(lo, lo);
1242 >                if (!toEnd)
1243 >                    m.compare(hi, hi);
1244              }
1055        }
1245  
1246 <        SubMap(boolean fromStart, K fromKey, boolean toEnd, K toKey) {
1246 >            this.m = m;
1247              this.fromStart = fromStart;
1248 <            this.fromKey= fromKey;
1248 >            this.lo = lo;
1249 >            this.loInclusive = loInclusive;
1250              this.toEnd = toEnd;
1251 <            this.toKey = toKey;
1251 >            this.hi = hi;
1252 >            this.hiInclusive = hiInclusive;
1253 >        }
1254 >
1255 >        // internal utilities
1256 >
1257 >        final boolean tooLow(Object key) {
1258 >            if (!fromStart) {
1259 >                int c = m.compare(key, lo);
1260 >                if (c < 0 || (c == 0 && !loInclusive))
1261 >                    return true;
1262 >            }
1263 >            return false;
1264 >        }
1265 >
1266 >        final boolean tooHigh(Object key) {
1267 >            if (!toEnd) {
1268 >                int c = m.compare(key, hi);
1269 >                if (c > 0 || (c == 0 && !hiInclusive))
1270 >                    return true;
1271 >            }
1272 >            return false;
1273 >        }
1274 >
1275 >        final boolean inRange(Object key) {
1276 >            return !tooLow(key) && !tooHigh(key);
1277          }
1278  
1279 +        final boolean inClosedRange(Object key) {
1280 +            return (fromStart || m.compare(key, lo) >= 0)
1281 +                && (toEnd || m.compare(hi, key) >= 0);
1282 +        }
1283 +
1284 +        final boolean inRange(Object key, boolean inclusive) {
1285 +            return inclusive ? inRange(key) : inClosedRange(key);
1286 +        }
1287 +
1288 +        /*
1289 +         * Absolute versions of relation operations.
1290 +         * Subclasses map to these using like-named "sub"
1291 +         * versions that invert senses for descending maps
1292 +         */
1293 +
1294 +        final TreeMap.Entry<K,V> absLowest() {
1295 +            TreeMap.Entry<K,V> e =
1296 +                (fromStart ?  m.getFirstEntry() :
1297 +                 (loInclusive ? m.getCeilingEntry(lo) :
1298 +                                m.getHigherEntry(lo)));
1299 +            return (e == null || tooHigh(e.key)) ? null : e;
1300 +        }
1301 +
1302 +        final TreeMap.Entry<K,V> absHighest() {
1303 +            TreeMap.Entry<K,V> e =
1304 +                (toEnd ?  m.getLastEntry() :
1305 +                 (hiInclusive ?  m.getFloorEntry(hi) :
1306 +                                 m.getLowerEntry(hi)));
1307 +            return (e == null || tooLow(e.key)) ? null : e;
1308 +        }
1309 +
1310 +        final TreeMap.Entry<K,V> absCeiling(K key) {
1311 +            if (tooLow(key))
1312 +                return absLowest();
1313 +            TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
1314 +            return (e == null || tooHigh(e.key)) ? null : e;
1315 +        }
1316 +
1317 +        final TreeMap.Entry<K,V> absHigher(K key) {
1318 +            if (tooLow(key))
1319 +                return absLowest();
1320 +            TreeMap.Entry<K,V> e = m.getHigherEntry(key);
1321 +            return (e == null || tooHigh(e.key)) ? null : e;
1322 +        }
1323 +
1324 +        final TreeMap.Entry<K,V> absFloor(K key) {
1325 +            if (tooHigh(key))
1326 +                return absHighest();
1327 +            TreeMap.Entry<K,V> e = m.getFloorEntry(key);
1328 +            return (e == null || tooLow(e.key)) ? null : e;
1329 +        }
1330 +
1331 +        final TreeMap.Entry<K,V> absLower(K key) {
1332 +            if (tooHigh(key))
1333 +                return absHighest();
1334 +            TreeMap.Entry<K,V> e = m.getLowerEntry(key);
1335 +            return (e == null || tooLow(e.key)) ? null : e;
1336 +        }
1337 +
1338 +        /** Returns the absolute high fence for ascending traversal */
1339 +        final TreeMap.Entry<K,V> absHighFence() {
1340 +            return (toEnd ? null : (hiInclusive ?
1341 +                                    m.getHigherEntry(hi) :
1342 +                                    m.getCeilingEntry(hi)));
1343 +        }
1344 +
1345 +        /** Return the absolute low fence for descending traversal  */
1346 +        final TreeMap.Entry<K,V> absLowFence() {
1347 +            return (fromStart ? null : (loInclusive ?
1348 +                                        m.getLowerEntry(lo) :
1349 +                                        m.getFloorEntry(lo)));
1350 +        }
1351 +
1352 +        // Abstract methods defined in ascending vs descending classes
1353 +        // These relay to the appropriate absolute versions
1354 +
1355 +        abstract TreeMap.Entry<K,V> subLowest();
1356 +        abstract TreeMap.Entry<K,V> subHighest();
1357 +        abstract TreeMap.Entry<K,V> subCeiling(K key);
1358 +        abstract TreeMap.Entry<K,V> subHigher(K key);
1359 +        abstract TreeMap.Entry<K,V> subFloor(K key);
1360 +        abstract TreeMap.Entry<K,V> subLower(K key);
1361 +
1362 +        /** Returns ascending iterator from the perspective of this submap */
1363 +        abstract Iterator<K> keyIterator();
1364 +
1365 +        /** Returns descending iterator from the perspective of this submap */
1366 +        abstract Iterator<K> descendingKeyIterator();
1367 +
1368 +        // public methods
1369 +
1370          public boolean isEmpty() {
1371 <            return entrySet().isEmpty();
1371 >            return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1372          }
1373  
1374 <        public boolean containsKey(Object key) {
1375 <            return inRange(key) && TreeMap.this.containsKey(key);
1374 >        public int size() {
1375 >            return (fromStart && toEnd) ? m.size() : entrySet().size();
1376          }
1377  
1378 <        public V get(Object key) {
1379 <            if (!inRange(key))
1074 <                return null;
1075 <            return TreeMap.this.get(key);
1378 >        public final boolean containsKey(Object key) {
1379 >            return inRange(key) && m.containsKey(key);
1380          }
1381  
1382 <        public V put(K key, V value) {
1382 >        public final V put(K key, V value) {
1383              if (!inRange(key))
1384                  throw new IllegalArgumentException("key out of range");
1385 <            return TreeMap.this.put(key, value);
1385 >            return m.put(key, value);
1386          }
1387  
1388 <        public V remove(Object key) {
1389 <            if (!inRange(key))
1086 <                return null;
1087 <            return TreeMap.this.remove(key);
1388 >        public final V get(Object key) {
1389 >            return !inRange(key)? null :  m.get(key);
1390          }
1391  
1392 <        public Comparator<? super K> comparator() {
1393 <            return comparator;
1392 >        public final V remove(Object key) {
1393 >            return !inRange(key)? null  : m.remove(key);
1394          }
1395  
1396 <        public K firstKey() {
1397 <            TreeMap.Entry<K,V> e = fromStart ? getFirstEntry() : getCeilingEntry(fromKey);
1096 <            K first = key(e);
1097 <            if (!toEnd && compare(first, toKey) >= 0)
1098 <                throw new NoSuchElementException();
1099 <            return first;
1396 >        public final Map.Entry<K,V> ceilingEntry(K key) {
1397 >            return exportEntry(subCeiling(key));
1398          }
1399  
1400 <        public K lastKey() {
1401 <            TreeMap.Entry<K,V> e = toEnd ? getLastEntry() : getLowerEntry(toKey);
1104 <            K last = key(e);
1105 <            if (!fromStart && compare(last, fromKey) < 0)
1106 <                throw new NoSuchElementException();
1107 <            return last;
1400 >        public final K ceilingKey(K key) {
1401 >            return keyOrNull(subCeiling(key));
1402          }
1403  
1404 <        public Map.Entry<K,V> firstEntry() {
1405 <            TreeMap.Entry<K,V> e = fromStart ?
1112 <                getFirstEntry() : getCeilingEntry(fromKey);
1113 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1114 <                return null;
1115 <            return e;
1404 >        public final Map.Entry<K,V> higherEntry(K key) {
1405 >            return exportEntry(subHigher(key));
1406          }
1407  
1408 <        public Map.Entry<K,V> lastEntry() {
1409 <            TreeMap.Entry<K,V> e = toEnd ?
1120 <                getLastEntry() : getLowerEntry(toKey);
1121 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1122 <                return null;
1123 <            return e;
1408 >        public final K higherKey(K key) {
1409 >            return keyOrNull(subHigher(key));
1410          }
1411  
1412 <        public Map.Entry<K,V> pollFirstEntry() {
1413 <            TreeMap.Entry<K,V> e = fromStart ?
1128 <                getFirstEntry() : getCeilingEntry(fromKey);
1129 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1130 <                return null;
1131 <            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1132 <            deleteEntry(e);
1133 <            return result;
1412 >        public final Map.Entry<K,V> floorEntry(K key) {
1413 >            return exportEntry(subFloor(key));
1414          }
1415  
1416 <        public Map.Entry<K,V> pollLastEntry() {
1417 <            TreeMap.Entry<K,V> e = toEnd ?
1138 <                getLastEntry() : getLowerEntry(toKey);
1139 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1140 <                return null;
1141 <            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1142 <            deleteEntry(e);
1143 <            return result;
1416 >        public final K floorKey(K key) {
1417 >            return keyOrNull(subFloor(key));
1418          }
1419  
1420 <        private TreeMap.Entry<K,V> subceiling(K key) {
1421 <            TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1148 <                getCeilingEntry(fromKey) : getCeilingEntry(key);
1149 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1150 <                return null;
1151 <            return e;
1420 >        public final Map.Entry<K,V> lowerEntry(K key) {
1421 >            return exportEntry(subLower(key));
1422          }
1423  
1424 <        public Map.Entry<K,V> ceilingEntry(K key) {
1425 <            TreeMap.Entry<K,V> e = subceiling(key);
1156 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1424 >        public final K lowerKey(K key) {
1425 >            return keyOrNull(subLower(key));
1426          }
1427  
1428 <        public K ceilingKey(K key) {
1429 <            TreeMap.Entry<K,V> e = subceiling(key);
1161 <            return e == null? null : e.key;
1428 >        public final K firstKey() {
1429 >            return key(subLowest());
1430          }
1431  
1432 <
1433 <        private TreeMap.Entry<K,V> subhigher(K key) {
1166 <            TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1167 <                getCeilingEntry(fromKey) : getHigherEntry(key);
1168 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1169 <                return null;
1170 <            return e;
1432 >        public final K lastKey() {
1433 >            return key(subHighest());
1434          }
1435  
1436 <        public Map.Entry<K,V> higherEntry(K key) {
1437 <            TreeMap.Entry<K,V> e = subhigher(key);
1175 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1436 >        public final Map.Entry<K,V> firstEntry() {
1437 >            return exportEntry(subLowest());
1438          }
1439  
1440 <        public K higherKey(K key) {
1441 <            TreeMap.Entry<K,V> e = subhigher(key);
1180 <            return e == null? null : e.key;
1440 >        public final Map.Entry<K,V> lastEntry() {
1441 >            return exportEntry(subHighest());
1442          }
1443  
1444 <        private TreeMap.Entry<K,V> subfloor(K key) {
1445 <            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1446 <                getLowerEntry(toKey) : getFloorEntry(key);
1447 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1448 <                return null;
1449 <            return e;
1444 >        public final Map.Entry<K,V> pollFirstEntry() {
1445 >            TreeMap.Entry<K,V> e = subLowest();
1446 >            Map.Entry<K,V> result = exportEntry(e);
1447 >            if (e != null)
1448 >                m.deleteEntry(e);
1449 >            return result;
1450          }
1451  
1452 <        public Map.Entry<K,V> floorEntry(K key) {
1453 <            TreeMap.Entry<K,V> e = subfloor(key);
1454 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1452 >        public final Map.Entry<K,V> pollLastEntry() {
1453 >            TreeMap.Entry<K,V> e = subHighest();
1454 >            Map.Entry<K,V> result = exportEntry(e);
1455 >            if (e != null)
1456 >                m.deleteEntry(e);
1457 >            return result;
1458          }
1459  
1460 <        public K floorKey(K key) {
1461 <            TreeMap.Entry<K,V> e = subfloor(key);
1462 <            return e == null? null : e.key;
1460 >        // Views
1461 >        transient NavigableMap<K,V> descendingMapView = null;
1462 >        transient EntrySetView entrySetView = null;
1463 >        transient KeySet<K> navigableKeySetView = null;
1464 >
1465 >        public final NavigableSet<K> navigableKeySet() {
1466 >            KeySet<K> nksv = navigableKeySetView;
1467 >            return (nksv != null) ? nksv :
1468 >                (navigableKeySetView = new TreeMap.KeySet(this));
1469          }
1470  
1471 <        private TreeMap.Entry<K,V> sublower(K key) {
1472 <            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1203 <                getLowerEntry(toKey) :  getLowerEntry(key);
1204 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1205 <                return null;
1206 <            return e;
1471 >        public final Set<K> keySet() {
1472 >            return navigableKeySet();
1473          }
1474  
1475 <        public Map.Entry<K,V> lowerEntry(K key) {
1476 <            TreeMap.Entry<K,V> e = sublower(key);
1211 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1475 >        public NavigableSet<K> descendingKeySet() {
1476 >            return descendingMap().navigableKeySet();
1477          }
1478  
1479 <        public K lowerKey(K key) {
1480 <            TreeMap.Entry<K,V> e = sublower(key);
1216 <            return e == null? null : e.key;
1479 >        public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1480 >            return subMap(fromKey, true, toKey, false);
1481          }
1482  
1483 <        private transient Set<Map.Entry<K,V>> entrySet = null;
1483 >        public final SortedMap<K,V> headMap(K toKey) {
1484 >            return headMap(toKey, false);
1485 >        }
1486  
1487 <        public Set<Map.Entry<K,V>> entrySet() {
1488 <            Set<Map.Entry<K,V>> es = entrySet;
1223 <            return (es != null)? es : (entrySet = new EntrySetView());
1487 >        public final SortedMap<K,V> tailMap(K fromKey) {
1488 >            return tailMap(fromKey, true);
1489          }
1490  
1491 <        private class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1491 >        // View classes
1492 >
1493 >        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1494              private transient int size = -1, sizeModCount;
1495  
1496              public int size() {
1497 <                if (size == -1 || sizeModCount != TreeMap.this.modCount) {
1498 <                    size = 0;  sizeModCount = TreeMap.this.modCount;
1497 >                if (fromStart && toEnd)
1498 >                    return m.size();
1499 >                if (size == -1 || sizeModCount != m.modCount) {
1500 >                    sizeModCount = m.modCount;
1501 >                    size = 0;
1502                      Iterator i = iterator();
1503                      while (i.hasNext()) {
1504                          size++;
# Line 1239 | Line 1509 | public class TreeMap<K,V>
1509              }
1510  
1511              public boolean isEmpty() {
1512 <                return !iterator().hasNext();
1512 >                TreeMap.Entry<K,V> n = absLowest();
1513 >                return n == null || tooHigh(n.key);
1514              }
1515  
1516              public boolean contains(Object o) {
# Line 1249 | Line 1520 | public class TreeMap<K,V>
1520                  K key = entry.getKey();
1521                  if (!inRange(key))
1522                      return false;
1523 <                TreeMap.Entry node = getEntry(key);
1523 >                TreeMap.Entry node = m.getEntry(key);
1524                  return node != null &&
1525 <                       valEquals(node.getValue(), entry.getValue());
1525 >                    valEquals(node.getValue(), entry.getValue());
1526              }
1527  
1528              public boolean remove(Object o) {
# Line 1261 | Line 1532 | public class TreeMap<K,V>
1532                  K key = entry.getKey();
1533                  if (!inRange(key))
1534                      return false;
1535 <                TreeMap.Entry<K,V> node = getEntry(key);
1535 >                TreeMap.Entry<K,V> node = m.getEntry(key);
1536                  if (node!=null && valEquals(node.getValue(),entry.getValue())){
1537 <                    deleteEntry(node);
1537 >                    m.deleteEntry(node);
1538                      return true;
1539                  }
1540                  return false;
1541              }
1271
1272            public Iterator<Map.Entry<K,V>> iterator() {
1273                return new SubMapEntryIterator(
1274                    (fromStart ? getFirstEntry() : getCeilingEntry(fromKey)),
1275                    (toEnd     ? null            : getCeilingEntry(toKey)));
1276            }
1542          }
1543  
1544 <        private transient Set<Map.Entry<K,V>> descendingEntrySetView = null;
1545 <        private transient Set<K> descendingKeySetView = null;
1546 <
1547 <        public Set<Map.Entry<K,V>> descendingEntrySet() {
1548 <            Set<Map.Entry<K,V>> es = descendingEntrySetView;
1549 <            return (es != null) ? es :
1550 <                (descendingEntrySetView = new DescendingEntrySetView());
1551 <        }
1287 <
1288 <        public Set<K> descendingKeySet() {
1289 <            Set<K> ks = descendingKeySetView;
1290 <            return (ks != null) ? ks :
1291 <                (descendingKeySetView = new DescendingKeySetView());
1292 <        }
1544 >        /**
1545 >         * Iterators for SubMaps
1546 >         */
1547 >        abstract class SubMapIterator<T> implements Iterator<T> {
1548 >            TreeMap.Entry<K,V> lastReturned;
1549 >            TreeMap.Entry<K,V> next;
1550 >            final K fenceKey;
1551 >            int expectedModCount;
1552  
1553 <        private class DescendingEntrySetView extends EntrySetView {
1554 <            public Iterator<Map.Entry<K,V>> iterator() {
1555 <                return new DescendingSubMapEntryIterator
1556 <                    ((toEnd     ? getLastEntry()  : getLowerEntry(toKey)),
1557 <                     (fromStart ? null            : getLowerEntry(fromKey)));
1553 >            SubMapIterator(TreeMap.Entry<K,V> first,
1554 >                           TreeMap.Entry<K,V> fence) {
1555 >                expectedModCount = m.modCount;
1556 >                lastReturned = null;
1557 >                next = first;
1558 >                fenceKey = fence == null ? null : fence.key;
1559              }
1300        }
1560  
1561 <        private class DescendingKeySetView extends AbstractSet<K> {
1562 <            public Iterator<K> iterator() {
1563 <                return new Iterator<K>() {
1305 <                    private Iterator<Entry<K,V>> i = descendingEntrySet().iterator();
1561 >            public final boolean hasNext() {
1562 >                return next != null && next.key != fenceKey;
1563 >            }
1564  
1565 <                    public boolean hasNext() { return i.hasNext(); }
1566 <                    public K next() { return i.next().getKey(); }
1567 <                    public void remove() { i.remove(); }
1568 <                };
1565 >            final TreeMap.Entry<K,V> nextEntry() {
1566 >                TreeMap.Entry<K,V> e = lastReturned = next;
1567 >                if (e == null || e.key == fenceKey)
1568 >                    throw new NoSuchElementException();
1569 >                if (m.modCount != expectedModCount)
1570 >                    throw new ConcurrentModificationException();
1571 >                next = successor(e);
1572 >                return e;
1573              }
1574  
1575 <            public int size() {
1576 <                return SubMap.this.size();
1575 >            final TreeMap.Entry<K,V> prevEntry() {
1576 >                TreeMap.Entry<K,V> e = lastReturned = next;
1577 >                if (e == null || e.key == fenceKey)
1578 >                    throw new NoSuchElementException();
1579 >                if (m.modCount != expectedModCount)
1580 >                    throw new ConcurrentModificationException();
1581 >                next = predecessor(e);
1582 >                return e;
1583              }
1584  
1585 <            public boolean contains(Object k) {
1586 <                return SubMap.this.containsKey(k);
1585 >            final void removeAscending() {
1586 >                if (lastReturned == null)
1587 >                    throw new IllegalStateException();
1588 >                if (m.modCount != expectedModCount)
1589 >                    throw new ConcurrentModificationException();
1590 >                // deleted entries are replaced by their successors
1591 >                if (lastReturned.left != null && lastReturned.right != null)
1592 >                    next = lastReturned;
1593 >                m.deleteEntry(lastReturned);
1594 >                lastReturned = null;
1595 >                expectedModCount = m.modCount;
1596              }
1320        }
1597  
1598 <        public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1599 <            if (!inRange2(fromKey))
1600 <                throw new IllegalArgumentException("fromKey out of range");
1601 <            if (!inRange2(toKey))
1602 <                throw new IllegalArgumentException("toKey out of range");
1603 <            return new SubMap(fromKey, toKey);
1604 <        }
1598 >            final void removeDescending() {
1599 >                if (lastReturned == null)
1600 >                    throw new IllegalStateException();
1601 >                if (m.modCount != expectedModCount)
1602 >                    throw new ConcurrentModificationException();
1603 >                m.deleteEntry(lastReturned);
1604 >                lastReturned = null;
1605 >                expectedModCount = m.modCount;
1606 >            }
1607  
1330        public NavigableMap<K,V> navigableHeadMap(K toKey) {
1331            if (!inRange2(toKey))
1332                throw new IllegalArgumentException("toKey out of range");
1333            return new SubMap(fromStart, fromKey, false, toKey);
1608          }
1609  
1610 <        public NavigableMap<K,V> navigableTailMap(K fromKey) {
1611 <            if (!inRange2(fromKey))
1612 <                throw new IllegalArgumentException("fromKey out of range");
1613 <            return new SubMap(false, fromKey, toEnd, toKey);
1614 <        }
1615 <
1616 <        public SortedMap<K,V> subMap(K fromKey, K toKey) {
1617 <            return navigableSubMap(fromKey, toKey);
1610 >        final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1611 >            SubMapEntryIterator(TreeMap.Entry<K,V> first,
1612 >                                TreeMap.Entry<K,V> fence) {
1613 >                super(first, fence);
1614 >            }
1615 >            public Map.Entry<K,V> next() {
1616 >                return nextEntry();
1617 >            }
1618 >            public void remove() {
1619 >                removeAscending();
1620 >            }
1621          }
1622  
1623 <        public SortedMap<K,V> headMap(K toKey) {
1624 <            return navigableHeadMap(toKey);
1623 >        final class SubMapKeyIterator extends SubMapIterator<K> {
1624 >            SubMapKeyIterator(TreeMap.Entry<K,V> first,
1625 >                              TreeMap.Entry<K,V> fence) {
1626 >                super(first, fence);
1627 >            }
1628 >            public K next() {
1629 >                return nextEntry().key;
1630 >            }
1631 >            public void remove() {
1632 >                removeAscending();
1633 >            }
1634          }
1635  
1636 <        public SortedMap<K,V> tailMap(K fromKey) {
1637 <            return navigableTailMap(fromKey);
1638 <        }
1636 >        final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1637 >            DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
1638 >                                          TreeMap.Entry<K,V> fence) {
1639 >                super(last, fence);
1640 >            }
1641  
1642 <        private boolean inRange(Object key) {
1643 <            return (fromStart || compare(key, fromKey) >= 0) &&
1644 <                   (toEnd     || compare(key, toKey)   <  0);
1642 >            public Map.Entry<K,V> next() {
1643 >                return prevEntry();
1644 >            }
1645 >            public void remove() {
1646 >                removeDescending();
1647 >            }
1648          }
1649  
1650 <        // This form allows the high endpoint (as well as all legit keys)
1651 <        private boolean inRange2(Object key) {
1652 <            return (fromStart || compare(key, fromKey) >= 0) &&
1653 <                   (toEnd     || compare(key, toKey)   <= 0);
1650 >        final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
1651 >            DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
1652 >                                        TreeMap.Entry<K,V> fence) {
1653 >                super(last, fence);
1654 >            }
1655 >            public K next() {
1656 >                return prevEntry().key;
1657 >            }
1658 >            public void remove() {
1659 >                removeDescending();
1660 >            }
1661          }
1662      }
1663  
1664      /**
1665 <     * TreeMap Iterator.
1665 >     * @serial include
1666       */
1667 <    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1668 <        int expectedModCount = TreeMap.this.modCount;
1371 <        Entry<K,V> lastReturned = null;
1372 <        Entry<K,V> next;
1667 >    static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1668 >        private static final long serialVersionUID = 912986545866124060L;
1669  
1670 <        PrivateEntryIterator(Entry<K,V> first) {
1671 <            next = first;
1670 >        AscendingSubMap(TreeMap<K,V> m,
1671 >                        boolean fromStart, K lo, boolean loInclusive,
1672 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1673 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1674          }
1675  
1676 <        public boolean hasNext() {
1677 <            return next != null;
1676 >        public Comparator<? super K> comparator() {
1677 >            return m.comparator();
1678          }
1679  
1680 <        Entry<K,V> nextEntry() {
1681 <            if (next == null)
1682 <                throw new NoSuchElementException();
1683 <            if (modCount != expectedModCount)
1684 <                throw new ConcurrentModificationException();
1685 <            lastReturned = next;
1686 <            next = successor(next);
1687 <            return lastReturned;
1680 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1681 >                                        K toKey,   boolean toInclusive) {
1682 >            if (!inRange(fromKey, fromInclusive))
1683 >                throw new IllegalArgumentException("fromKey out of range");
1684 >            if (!inRange(toKey, toInclusive))
1685 >                throw new IllegalArgumentException("toKey out of range");
1686 >            return new AscendingSubMap(m,
1687 >                                       false, fromKey, fromInclusive,
1688 >                                       false, toKey,   toInclusive);
1689          }
1690  
1691 <        public void remove() {
1692 <            if (lastReturned == null)
1693 <                throw new IllegalStateException();
1694 <            if (modCount != expectedModCount)
1695 <                throw new ConcurrentModificationException();
1696 <            if (lastReturned.left != null && lastReturned.right != null)
1398 <                next = lastReturned;
1399 <            deleteEntry(lastReturned);
1400 <            expectedModCount++;
1401 <            lastReturned = null;
1691 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1692 >            if (!inClosedRange(toKey))
1693 >                throw new IllegalArgumentException("toKey out of range");
1694 >            return new AscendingSubMap(m,
1695 >                                       fromStart, lo,    loInclusive,
1696 >                                       false,     toKey, inclusive);
1697          }
1403    }
1698  
1699 <    class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1700 <        EntryIterator(Entry<K,V> first) {
1701 <            super(first);
1702 <        }
1703 <        public Map.Entry<K,V> next() {
1704 <            return nextEntry();
1699 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1700 >            if (!inRange(fromKey, inclusive))
1701 >                throw new IllegalArgumentException("fromKey out of range");
1702 >            return new AscendingSubMap(m,
1703 >                                       false, fromKey, inclusive,
1704 >                                       toEnd, hi,      hiInclusive);
1705          }
1412    }
1706  
1707 <    class KeyIterator extends PrivateEntryIterator<K> {
1708 <        KeyIterator(Entry<K,V> first) {
1709 <            super(first);
1710 <        }
1711 <        public K next() {
1712 <            return nextEntry().key;
1707 >        public NavigableMap<K,V> descendingMap() {
1708 >            NavigableMap<K,V> mv = descendingMapView;
1709 >            return (mv != null) ? mv :
1710 >                (descendingMapView =
1711 >                 new DescendingSubMap(m,
1712 >                                      fromStart, lo, loInclusive,
1713 >                                      toEnd,     hi, hiInclusive));
1714          }
1421    }
1715  
1716 <    class ValueIterator extends PrivateEntryIterator<V> {
1717 <        ValueIterator(Entry<K,V> first) {
1425 <            super(first);
1716 >        Iterator<K> keyIterator() {
1717 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1718          }
1427        public V next() {
1428            return nextEntry().value;
1429        }
1430    }
1719  
1720 <    class SubMapEntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1721 <        private final K firstExcludedKey;
1434 <
1435 <        SubMapEntryIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1436 <            super(first);
1437 <            firstExcludedKey = (firstExcluded == null
1438 <                                ? null
1439 <                                : firstExcluded.key);
1720 >        Iterator<K> descendingKeyIterator() {
1721 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1722          }
1723  
1724 <        public boolean hasNext() {
1725 <            return next != null && next.key != firstExcludedKey;
1724 >        final class AscendingEntrySetView extends EntrySetView {
1725 >            public Iterator<Map.Entry<K,V>> iterator() {
1726 >                return new SubMapEntryIterator(absLowest(), absHighFence());
1727 >            }
1728          }
1729  
1730 <        public Map.Entry<K,V> next() {
1731 <            if (next == null || next.key == firstExcludedKey)
1732 <                throw new NoSuchElementException();
1449 <            return nextEntry();
1730 >        public Set<Map.Entry<K,V>> entrySet() {
1731 >            EntrySetView es = entrySetView;
1732 >            return (es != null) ? es : new AscendingEntrySetView();
1733          }
1734 +
1735 +        TreeMap.Entry<K,V> subLowest()       { return absLowest(); }
1736 +        TreeMap.Entry<K,V> subHighest()      { return absHighest(); }
1737 +        TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); }
1738 +        TreeMap.Entry<K,V> subHigher(K key)  { return absHigher(key); }
1739 +        TreeMap.Entry<K,V> subFloor(K key)   { return absFloor(key); }
1740 +        TreeMap.Entry<K,V> subLower(K key)   { return absLower(key); }
1741      }
1742  
1743      /**
1744 <     * Base for Descending Iterators.
1744 >     * @serial include
1745       */
1746 <    abstract class DescendingPrivateEntryIterator<T> extends PrivateEntryIterator<T> {
1747 <        DescendingPrivateEntryIterator(Entry<K,V> first) {
1748 <            super(first);
1746 >    static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
1747 >        private static final long serialVersionUID = 912986545866120460L;
1748 >        DescendingSubMap(TreeMap<K,V> m,
1749 >                        boolean fromStart, K lo, boolean loInclusive,
1750 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1751 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1752          }
1753  
1754 <        Entry<K,V> nextEntry() {
1755 <            if (next == null)
1463 <                throw new NoSuchElementException();
1464 <            if (modCount != expectedModCount)
1465 <                throw new ConcurrentModificationException();
1466 <            lastReturned = next;
1467 <            next = predecessor(next);
1468 <            return lastReturned;
1469 <        }
1470 <    }
1754 >        private final Comparator<? super K> reverseComparator =
1755 >            Collections.reverseOrder(m.comparator);
1756  
1757 <    class DescendingEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1758 <        DescendingEntryIterator(Entry<K,V> first) {
1474 <            super(first);
1757 >        public Comparator<? super K> comparator() {
1758 >            return reverseComparator;
1759          }
1760 <        public Map.Entry<K,V> next() {
1761 <            return nextEntry();
1760 >
1761 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1762 >                                        K toKey,   boolean toInclusive) {
1763 >            if (!inRange(fromKey, fromInclusive))
1764 >                throw new IllegalArgumentException("fromKey out of range");
1765 >            if (!inRange(toKey, toInclusive))
1766 >                throw new IllegalArgumentException("toKey out of range");
1767 >            return new DescendingSubMap(m,
1768 >                                        false, toKey,   toInclusive,
1769 >                                        false, fromKey, fromInclusive);
1770          }
1479    }
1771  
1772 <    class DescendingKeyIterator extends DescendingPrivateEntryIterator<K> {
1773 <        DescendingKeyIterator(Entry<K,V> first) {
1774 <            super(first);
1772 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1773 >            if (!inRange(toKey, inclusive))
1774 >                throw new IllegalArgumentException("toKey out of range");
1775 >            return new DescendingSubMap(m,
1776 >                                        false, toKey, inclusive,
1777 >                                        toEnd, hi,    hiInclusive);
1778          }
1779 <        public K next() {
1780 <            return nextEntry().key;
1779 >
1780 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1781 >            if (!inRange(fromKey, inclusive))
1782 >                throw new IllegalArgumentException("fromKey out of range");
1783 >            return new DescendingSubMap(m,
1784 >                                        fromStart, lo, loInclusive,
1785 >                                        false, fromKey, inclusive);
1786          }
1488    }
1787  
1788 +        public NavigableMap<K,V> descendingMap() {
1789 +            NavigableMap<K,V> mv = descendingMapView;
1790 +            return (mv != null) ? mv :
1791 +                (descendingMapView =
1792 +                 new AscendingSubMap(m,
1793 +                                     fromStart, lo, loInclusive,
1794 +                                     toEnd,     hi, hiInclusive));
1795 +        }
1796  
1797 <    class DescendingSubMapEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1798 <        private final K lastExcludedKey;
1797 >        Iterator<K> keyIterator() {
1798 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1799 >        }
1800  
1801 <        DescendingSubMapEntryIterator(Entry<K,V> last, Entry<K,V> lastExcluded) {
1802 <            super(last);
1496 <            lastExcludedKey = (lastExcluded == null
1497 <                                ? null
1498 <                                : lastExcluded.key);
1801 >        Iterator<K> descendingKeyIterator() {
1802 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1803          }
1804  
1805 <        public boolean hasNext() {
1806 <            return next != null && next.key != lastExcludedKey;
1805 >        final class DescendingEntrySetView extends EntrySetView {
1806 >            public Iterator<Map.Entry<K,V>> iterator() {
1807 >                return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
1808 >            }
1809          }
1810  
1811 <        public Map.Entry<K,V> next() {
1812 <            if (next == null || next.key == lastExcludedKey)
1813 <                throw new NoSuchElementException();
1508 <            return nextEntry();
1811 >        public Set<Map.Entry<K,V>> entrySet() {
1812 >            EntrySetView es = entrySetView;
1813 >            return (es != null) ? es : new DescendingEntrySetView();
1814          }
1815  
1816 +        TreeMap.Entry<K,V> subLowest()       { return absHighest(); }
1817 +        TreeMap.Entry<K,V> subHighest()      { return absLowest(); }
1818 +        TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
1819 +        TreeMap.Entry<K,V> subHigher(K key)  { return absLower(key); }
1820 +        TreeMap.Entry<K,V> subFloor(K key)   { return absCeiling(key); }
1821 +        TreeMap.Entry<K,V> subLower(K key)   { return absHigher(key); }
1822      }
1823  
1824      /**
1825 <     * Compares two keys using the correct comparison method for this TreeMap.
1825 >     * This class exists solely for the sake of serialization
1826 >     * compatibility with previous releases of TreeMap that did not
1827 >     * support NavigableMap.  It translates an old-version SubMap into
1828 >     * a new-version AscendingSubMap. This class is never otherwise
1829 >     * used.
1830 >     *
1831 >     * @serial include
1832       */
1833 <    private int compare(Object k1, Object k2) {
1834 <        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1835 <                                : comparator.compare((K)k1, (K)k2);
1833 >    private class SubMap extends AbstractMap<K,V>
1834 >        implements SortedMap<K,V>, java.io.Serializable {
1835 >        private static final long serialVersionUID = -6520786458950516097L;
1836 >        private boolean fromStart = false, toEnd = false;
1837 >        private K fromKey, toKey;
1838 >        private Object readResolve() {
1839 >            return new AscendingSubMap(TreeMap.this,
1840 >                                       fromStart, fromKey, true,
1841 >                                       toEnd, toKey, false);
1842 >        }
1843 >        public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
1844 >        public K lastKey() { throw new InternalError(); }
1845 >        public K firstKey() { throw new InternalError(); }
1846 >        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
1847 >        public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
1848 >        public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
1849 >        public Comparator<? super K> comparator() { throw new InternalError(); }
1850      }
1851  
1852 <    /**
1853 <     * Test two values  for equality.  Differs from o1.equals(o2) only in
1523 <     * that it copes with <tt>null</tt> o1 properly.
1524 <     */
1525 <    private static boolean valEquals(Object o1, Object o2) {
1526 <        return (o1==null ? o2==null : o1.equals(o2));
1527 <    }
1852 >
1853 >    // Red-black mechanics
1854  
1855      private static final boolean RED   = false;
1856      private static final boolean BLACK = true;
# Line 1534 | Line 1860 | public class TreeMap<K,V>
1860       * user (see Map.Entry).
1861       */
1862  
1863 <    static class Entry<K,V> implements Map.Entry<K,V> {
1863 >    static final class Entry<K,V> implements Map.Entry<K,V> {
1864          K key;
1865          V value;
1866          Entry<K,V> left = null;
# Line 1586 | Line 1912 | public class TreeMap<K,V>
1912          public boolean equals(Object o) {
1913              if (!(o instanceof Map.Entry))
1914                  return false;
1915 <            Map.Entry e = (Map.Entry)o;
1915 >            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1916  
1917              return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
1918          }
# Line 1606 | Line 1932 | public class TreeMap<K,V>
1932       * Returns the first Entry in the TreeMap (according to the TreeMap's
1933       * key-sort function).  Returns null if the TreeMap is empty.
1934       */
1935 <    private Entry<K,V> getFirstEntry() {
1935 >    final Entry<K,V> getFirstEntry() {
1936          Entry<K,V> p = root;
1937          if (p != null)
1938              while (p.left != null)
# Line 1618 | Line 1944 | public class TreeMap<K,V>
1944       * Returns the last Entry in the TreeMap (according to the TreeMap's
1945       * key-sort function).  Returns null if the TreeMap is empty.
1946       */
1947 <    private Entry<K,V> getLastEntry() {
1947 >    final Entry<K,V> getLastEntry() {
1948          Entry<K,V> p = root;
1949          if (p != null)
1950              while (p.right != null)
# Line 1629 | Line 1955 | public class TreeMap<K,V>
1955      /**
1956       * Returns the successor of the specified Entry, or null if no such.
1957       */
1958 <    private Entry<K,V> successor(Entry<K,V> t) {
1958 >    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
1959          if (t == null)
1960              return null;
1961          else if (t.right != null) {
# Line 1651 | Line 1977 | public class TreeMap<K,V>
1977      /**
1978       * Returns the predecessor of the specified Entry, or null if no such.
1979       */
1980 <    private Entry<K,V> predecessor(Entry<K,V> t) {
1980 >    static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {
1981          if (t == null)
1982              return null;
1983          else if (t.left != null) {
# Line 1701 | Line 2027 | public class TreeMap<K,V>
2027          return (p == null) ? null: p.right;
2028      }
2029  
2030 <    /** From CLR **/
2030 >    /** From CLR */
2031      private void rotateLeft(Entry<K,V> p) {
2032 <        Entry<K,V> r = p.right;
2033 <        p.right = r.left;
2034 <        if (r.left != null)
2035 <            r.left.parent = p;
2036 <        r.parent = p.parent;
2037 <        if (p.parent == null)
2038 <            root = r;
2039 <        else if (p.parent.left == p)
2040 <            p.parent.left = r;
2041 <        else
2042 <            p.parent.right = r;
2043 <        r.left = p;
2044 <        p.parent = r;
2032 >        if (p != null) {
2033 >            Entry<K,V> r = p.right;
2034 >            p.right = r.left;
2035 >            if (r.left != null)
2036 >                r.left.parent = p;
2037 >            r.parent = p.parent;
2038 >            if (p.parent == null)
2039 >                root = r;
2040 >            else if (p.parent.left == p)
2041 >                p.parent.left = r;
2042 >            else
2043 >                p.parent.right = r;
2044 >            r.left = p;
2045 >            p.parent = r;
2046 >        }
2047      }
2048  
2049 <    /** From CLR **/
2049 >    /** From CLR */
2050      private void rotateRight(Entry<K,V> p) {
2051 <        Entry<K,V> l = p.left;
2052 <        p.left = l.right;
2053 <        if (l.right != null) l.right.parent = p;
2054 <        l.parent = p.parent;
2055 <        if (p.parent == null)
2056 <            root = l;
2057 <        else if (p.parent.right == p)
2058 <            p.parent.right = l;
2059 <        else p.parent.left = l;
2060 <        l.right = p;
2061 <        p.parent = l;
2051 >        if (p != null) {
2052 >            Entry<K,V> l = p.left;
2053 >            p.left = l.right;
2054 >            if (l.right != null) l.right.parent = p;
2055 >            l.parent = p.parent;
2056 >            if (p.parent == null)
2057 >                root = l;
2058 >            else if (p.parent.right == p)
2059 >                p.parent.right = l;
2060 >            else p.parent.left = l;
2061 >            l.right = p;
2062 >            p.parent = l;
2063 >        }
2064      }
2065  
2066 <
1737 <    /** From CLR **/
2066 >    /** From CLR */
2067      private void fixAfterInsertion(Entry<K,V> x) {
2068          x.color = RED;
2069  
# Line 1753 | Line 2082 | public class TreeMap<K,V>
2082                      }
2083                      setColor(parentOf(x), BLACK);
2084                      setColor(parentOf(parentOf(x)), RED);
2085 <                    if (parentOf(parentOf(x)) != null)
1757 <                        rotateRight(parentOf(parentOf(x)));
2085 >                    rotateRight(parentOf(parentOf(x)));
2086                  }
2087              } else {
2088                  Entry<K,V> y = leftOf(parentOf(parentOf(x)));
# Line 1768 | Line 2096 | public class TreeMap<K,V>
2096                          x = parentOf(x);
2097                          rotateRight(x);
2098                      }
2099 <                    setColor(parentOf(x),  BLACK);
2099 >                    setColor(parentOf(x), BLACK);
2100                      setColor(parentOf(parentOf(x)), RED);
2101 <                    if (parentOf(parentOf(x)) != null)
1774 <                        rotateLeft(parentOf(parentOf(x)));
2101 >                    rotateLeft(parentOf(parentOf(x)));
2102                  }
2103              }
2104          }
# Line 1781 | Line 2108 | public class TreeMap<K,V>
2108      /**
2109       * Delete node p, and then rebalance the tree.
2110       */
1784
2111      private void deleteEntry(Entry<K,V> p) {
2112 <        decrementSize();
2112 >        modCount++;
2113 >        size--;
2114  
2115          // If strictly internal, copy successor's element to p and then make p
2116          // point to successor.
# Line 1829 | Line 2156 | public class TreeMap<K,V>
2156          }
2157      }
2158  
2159 <    /** From CLR **/
2159 >    /** From CLR */
2160      private void fixAfterDeletion(Entry<K,V> x) {
2161          while (x != root && colorOf(x) == BLACK) {
2162              if (x == leftOf(parentOf(x))) {
# Line 1844 | Line 2171 | public class TreeMap<K,V>
2171  
2172                  if (colorOf(leftOf(sib))  == BLACK &&
2173                      colorOf(rightOf(sib)) == BLACK) {
2174 <                    setColor(sib,  RED);
2174 >                    setColor(sib, RED);
2175                      x = parentOf(x);
2176                  } else {
2177                      if (colorOf(rightOf(sib)) == BLACK) {
# Line 1871 | Line 2198 | public class TreeMap<K,V>
2198  
2199                  if (colorOf(rightOf(sib)) == BLACK &&
2200                      colorOf(leftOf(sib)) == BLACK) {
2201 <                    setColor(sib,  RED);
2201 >                    setColor(sib, RED);
2202                      x = parentOf(x);
2203                  } else {
2204                      if (colorOf(leftOf(sib)) == BLACK) {
# Line 1922 | Line 2249 | public class TreeMap<K,V>
2249          }
2250      }
2251  
1925
1926
2252      /**
2253       * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e.,
2254       * deserialize it).
# Line 1939 | Line 2264 | public class TreeMap<K,V>
2264          buildFromSorted(size, null, s, null);
2265      }
2266  
2267 <    /** Intended to be called only from TreeSet.readObject **/
2267 >    /** Intended to be called only from TreeSet.readObject */
2268      void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2269          throws java.io.IOException, ClassNotFoundException {
2270          buildFromSorted(size, null, s, defaultVal);
2271      }
2272  
2273 <    /** Intended to be called only from TreeSet.addAll **/
2273 >    /** Intended to be called only from TreeSet.addAll */
2274      void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2275          try {
2276              buildFromSorted(set.size(), set.iterator(), null, defaultVal);
# Line 1985 | Line 2310 | public class TreeMap<K,V>
2310       * @throws ClassNotFoundException propagated from readObject.
2311       *         This cannot occur if str is null.
2312       */
2313 <    private
2314 <    void buildFromSorted(int size, Iterator it,
2315 <                         java.io.ObjectInputStream str,
1991 <                         V defaultVal)
2313 >    private void buildFromSorted(int size, Iterator it,
2314 >                                 java.io.ObjectInputStream str,
2315 >                                 V defaultVal)
2316          throws  java.io.IOException, ClassNotFoundException {
2317          this.size = size;
2318 <        root =
2319 <            buildFromSorted(0, 0, size-1, computeRedLevel(size),
1996 <                            it, str, defaultVal);
2318 >        root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
2319 >                               it, str, defaultVal);
2320      }
2321  
2322      /**
2323       * Recursive "helper method" that does the real work of the
2324 <     * of the previous method.  Identically named parameters have
2324 >     * previous method.  Identically named parameters have
2325       * identical definitions.  Additional parameters are documented below.
2326       * It is assumed that the comparator and size fields of the TreeMap are
2327       * already set prior to calling this method.  (It ignores both fields.)

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines