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.28 by dl, Wed Apr 19 15:07:14 2006 UTC vs.
Revision 1.34 by dl, Sun Apr 23 20:59:49 2006 UTC

# Line 95 | 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 110 | public class TreeMap<K,V>
110      private transient int modCount = 0;
111  
112      /**
113     * A sentinel to indicate that an endpoint of a submap is not bounded.
114     * It is used to generate head maps, tail maps, and descending views
115     * of the entire backing map. The sentinel must be serializable,
116     * requiring a little class to express.
117     */
118    private static class Unbounded implements java.io.Serializable {}
119    private static final Unbounded UNBOUNDED = new Unbounded();
120
121    private void incrementSize()   { modCount++; size++; }
122    private void decrementSize()   { modCount++; size--; }
123
124    /**
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
115       * Comparable} interface.  Furthermore, all such keys must be
# Line 134 | Line 122 | public class TreeMap<K,V>
122       * <tt>ClassCastException</tt>.
123       */
124      public TreeMap() {
125 +        comparator = null;
126      }
127  
128      /**
# Line 169 | 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 233 | 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 <    }
240 <
241 <    private boolean valueSearchNull(Entry n) {
242 <        if (n.value == null)
243 <            return true;
244 <
245 <        // Check left and right subtrees for value
246 <        return (n.left  != null && valueSearchNull(n.left)) ||
247 <               (n.right != null && valueSearchNull(n.right));
248 <    }
249 <
250 <    private boolean valueSearchNonNull(Entry n, Object value) {
251 <        // Check this node for the value
252 <        if (value.equals(n.value))
253 <            return true;
254 <
255 <        // Check left and right subtrees for value
256 <        return (n.left  != null && valueSearchNonNull(n.left, value)) ||
257 <               (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      /**
# Line 344 | 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);
# Line 370 | 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 392 | 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)
398 <            return null;
399 <
400 <        while (true) {
371 >        while (p != null) {
372              int cmp = compare(key, p.key);
373              if (cmp < 0) {
374                  if (p.left != null)
# Line 419 | Line 390 | public class TreeMap<K,V>
390              } else
391                  return p;
392          }
393 +        return null;
394      }
395  
396      /**
# Line 426 | 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)
432 <            return null;
433 <
434 <        while (true) {
403 >        while (p != null) {
404              int cmp = compare(key, p.key);
405              if (cmp > 0) {
406                  if (p.right != null)
# Line 454 | Line 423 | public class TreeMap<K,V>
423                  return p;
424  
425          }
426 +        return null;
427      }
428  
429      /**
# Line 462 | 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)
468 <            return null;
469 <
470 <        while (true) {
437 >        while (p != null) {
438              int cmp = compare(key, p.key);
439              if (cmp < 0) {
440                  if (p.left != null)
# Line 488 | Line 455 | public class TreeMap<K,V>
455                  }
456              }
457          }
458 +        return null;
459      }
460  
461      /**
# Line 495 | 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)
501 <            return null;
502 <
503 <        while (true) {
468 >        while (p != null) {
469              int cmp = compare(key, p.key);
470              if (cmp > 0) {
471                  if (p.right != null)
# Line 521 | Line 486 | public class TreeMap<K,V>
486                  }
487              }
488          }
489 <    }
525 <
526 <    /**
527 <     * Returns the key corresponding to the specified Entry.
528 <     * @throws NoSuchElementException if the Entry is null
529 <     */
530 <    private static <K> K key(Entry<K,?> e) {
531 <        if (e==null)
532 <            throw new NoSuchElementException();
533 <        return e.key;
489 >        return null;
490      }
491  
492      /**
# Line 553 | Line 509 | public class TreeMap<K,V>
509       */
510      public V put(K key, V value) {
511          Entry<K,V> t = root;
556
512          if (t == null) {
513 <            // TBD
559 < //             if (key == null) {
560 < //                 if (comparator == null)
561 < //                     throw new NullPointerException();
562 < //                 comparator.compare(key, key);
563 < //             }
564 <            incrementSize();
513 >            compare(key, key); // type check
514              root = new Entry<K,V>(key, value, null);
515 +            size = 1;
516 +            modCount++;
517              return null;
518          }
519 <
520 <        while (true) {
521 <            int cmp = compare(key, t.key);
522 <            if (cmp == 0) {
523 <                return t.setValue(value);
524 <            } else if (cmp < 0) {
525 <                if (t.left != null) {
519 >        int cmp;
520 >        Entry<K,V> parent;
521 >        // split comparator and comparable paths
522 >        Comparator<? super K> cpr = comparator;
523 >        if (cpr != null) {
524 >            do {
525 >                parent = t;
526 >                cmp = cpr.compare(key, t.key);
527 >                if (cmp < 0)
528                      t = t.left;
529 <                } else {
577 <                    incrementSize();
578 <                    t.left = new Entry<K,V>(key, value, t);
579 <                    fixAfterInsertion(t.left);
580 <                    return null;
581 <                }
582 <            } else { // cmp > 0
583 <                if (t.right != null) {
529 >                else if (cmp > 0)
530                      t = t.right;
531 <                } else {
532 <                    incrementSize();
533 <                    t.right = new Entry<K,V>(key, value, t);
588 <                    fixAfterInsertion(t.right);
589 <                    return null;
590 <                }
591 <            }
531 >                else
532 >                    return t.setValue(value);
533 >            } while (t != null);
534          }
535 +        else {
536 +            if (key == null)
537 +                throw new NullPointerException();
538 +            Comparable<? super K> k = (Comparable<? super K>) key;
539 +            do {
540 +                parent = t;
541 +                cmp = k.compareTo(t.key);
542 +                if (cmp < 0)
543 +                    t = t.left;
544 +                else if (cmp > 0)
545 +                    t = t.right;
546 +                else
547 +                    return t.setValue(value);
548 +            } while (t != null);
549 +        }
550 +        Entry<K,V> e = new Entry<K,V>(key, value, parent);
551 +        if (cmp < 0)
552 +            parent.left = e;
553 +        else
554 +            parent.right = e;
555 +        fixAfterInsertion(e);
556 +        size++;
557 +        modCount++;
558 +        return null;
559      }
560  
561      /**
# Line 664 | Line 630 | public class TreeMap<K,V>
630       * @since 1.6
631       */
632      public Map.Entry<K,V> firstEntry() {
633 <        Entry<K,V> e = getFirstEntry();
668 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
633 >        return exportEntry(getFirstEntry());
634      }
635  
636      /**
637       * @since 1.6
638       */
639      public Map.Entry<K,V> lastEntry() {
640 <        Entry<K,V> e = getLastEntry();
676 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
640 >        return exportEntry(getLastEntry());
641      }
642  
643      /**
# Line 681 | Line 645 | public class TreeMap<K,V>
645       */
646      public Map.Entry<K,V> pollFirstEntry() {
647          Entry<K,V> p = getFirstEntry();
648 <        if (p == null)
649 <            return null;
650 <        Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(p);
687 <        deleteEntry(p);
648 >        Map.Entry<K,V> result = exportEntry(p);
649 >        if (p != null)
650 >            deleteEntry(p);
651          return result;
652      }
653  
# Line 693 | Line 656 | public class TreeMap<K,V>
656       */
657      public Map.Entry<K,V> pollLastEntry() {
658          Entry<K,V> p = getLastEntry();
659 <        if (p == null)
660 <            return null;
661 <        Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(p);
699 <        deleteEntry(p);
659 >        Map.Entry<K,V> result = exportEntry(p);
660 >        if (p != null)
661 >            deleteEntry(p);
662          return result;
663      }
664  
# Line 708 | Line 670 | public class TreeMap<K,V>
670       * @since 1.6
671       */
672      public Map.Entry<K,V> lowerEntry(K key) {
673 <        Entry<K,V> e =  getLowerEntry(key);
712 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
673 >        return exportEntry(getLowerEntry(key));
674      }
675  
676      /**
# Line 720 | Line 681 | public class TreeMap<K,V>
681       * @since 1.6
682       */
683      public K lowerKey(K key) {
684 <        Entry<K,V> e =  getLowerEntry(key);
724 <        return (e == null)? null : e.key;
684 >        return keyOrNull(getLowerEntry(key));
685      }
686  
687      /**
# Line 732 | Line 692 | public class TreeMap<K,V>
692       * @since 1.6
693       */
694      public Map.Entry<K,V> floorEntry(K key) {
695 <        Entry<K,V> e = getFloorEntry(key);
736 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
695 >        return exportEntry(getFloorEntry(key));
696      }
697  
698      /**
# Line 744 | Line 703 | public class TreeMap<K,V>
703       * @since 1.6
704       */
705      public K floorKey(K key) {
706 <        Entry<K,V> e = getFloorEntry(key);
748 <        return (e == null)? null : e.key;
706 >        return keyOrNull(getFloorEntry(key));
707      }
708  
709      /**
# Line 756 | Line 714 | public class TreeMap<K,V>
714       * @since 1.6
715       */
716      public Map.Entry<K,V> ceilingEntry(K key) {
717 <        Entry<K,V> e = getCeilingEntry(key);
760 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
717 >        return exportEntry(getCeilingEntry(key));
718      }
719  
720      /**
# Line 768 | Line 725 | public class TreeMap<K,V>
725       * @since 1.6
726       */
727      public K ceilingKey(K key) {
728 <        Entry<K,V> e = getCeilingEntry(key);
772 <        return (e == null)? null : e.key;
728 >        return keyOrNull(getCeilingEntry(key));
729      }
730  
731      /**
# Line 780 | Line 736 | public class TreeMap<K,V>
736       * @since 1.6
737       */
738      public Map.Entry<K,V> higherEntry(K key) {
739 <        Entry<K,V> e = getHigherEntry(key);
784 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
739 >        return exportEntry(getHigherEntry(key));
740      }
741  
742      /**
# Line 792 | Line 747 | public class TreeMap<K,V>
747       * @since 1.6
748       */
749      public K higherKey(K key) {
750 <        Entry<K,V> e = getHigherEntry(key);
796 <        return (e == null)? null : e.key;
750 >        return keyOrNull(getHigherEntry(key));
751      }
752  
753      // Views
# Line 803 | Line 757 | public class TreeMap<K,V>
757       * the first time this view is requested.  Views are stateless, so
758       * there's no reason to create more than one.
759       */
760 <    private transient Set<Map.Entry<K,V>> entrySet = null;
760 >    private transient EntrySet entrySet = null;
761      private transient KeySet<K> navigableKeySet = null;
762      private transient NavigableMap<K,V> descendingMap = null;
763  
# Line 829 | Line 783 | public class TreeMap<K,V>
783       * @since 1.6
784       */
785      public NavigableSet<K> navigableKeySet() {
786 <        NavigableSet<K> nks = navigableKeySet;
786 >        KeySet<K> nks = navigableKeySet;
787          return (nks != null) ? nks : (navigableKeySet = new KeySet(this));
788      }
789  
# Line 876 | Line 830 | public class TreeMap<K,V>
830       * <tt>add</tt> or <tt>addAll</tt> operations.
831       */
832      public Set<Map.Entry<K,V>> entrySet() {
833 <        Set<Map.Entry<K,V>> es = entrySet;
833 >        EntrySet es = entrySet;
834          return (es != null) ? es : (entrySet = new EntrySet());
835      }
836  
# Line 886 | Line 840 | public class TreeMap<K,V>
840      public NavigableMap<K, V> descendingMap() {
841          NavigableMap<K, V> km = descendingMap;
842          return (km != null) ? km :
843 <            (descendingMap = new DescendingSubMap((K)UNBOUNDED, 0,
844 <                                                  (K)UNBOUNDED, 0));
843 >            (descendingMap = new DescendingSubMap(this,
844 >                                                  true, null, true,
845 >                                                  true, null, true));
846      }
847  
848      /**
# Line 898 | Line 853 | public class TreeMap<K,V>
853       * @throws IllegalArgumentException {@inheritDoc}
854       * @since 1.6
855       */
856 <    public NavigableMap<K,V> navigableSubMap(K fromKey, boolean fromInclusive,
857 <                                             K toKey,   boolean toInclusive) {
858 <        return new AscendingSubMap(fromKey, excluded(fromInclusive),
859 <                                   toKey,   excluded(toInclusive));
856 >    public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
857 >                                    K toKey,   boolean toInclusive) {
858 >        return new AscendingSubMap(this,
859 >                                   false, fromKey, fromInclusive,
860 >                                   false, toKey,   toInclusive);
861      }
862  
863      /**
# Line 912 | Line 868 | public class TreeMap<K,V>
868       * @throws IllegalArgumentException {@inheritDoc}
869       * @since 1.6
870       */
871 <    public NavigableMap<K,V> navigableHeadMap(K toKey, boolean inclusive) {
872 <        return new AscendingSubMap((K)UNBOUNDED, 0, toKey, excluded(inclusive));
871 >    public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
872 >        return new AscendingSubMap(this,
873 >                                   true,  null,  true,
874 >                                   false, toKey, inclusive);
875      }
876  
877      /**
# Line 924 | Line 882 | public class TreeMap<K,V>
882       * @throws IllegalArgumentException {@inheritDoc}
883       * @since 1.6
884       */
885 <    public NavigableMap<K,V> navigableTailMap(K fromKey, boolean inclusive) {
886 <        return new AscendingSubMap(fromKey, excluded(inclusive), (K)UNBOUNDED, 0);
887 <    }
888 <
931 <    /**
932 <     * Translates a boolean "inclusive" value to the correct int value
933 <     * for the loExcluded or hiExcluded field.
934 <     */
935 <    static int excluded(boolean inclusive) {
936 <        return inclusive ? 0 : 1;
885 >    public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
886 >        return new AscendingSubMap(this,
887 >                                   false, fromKey, inclusive,
888 >                                   true,  null,    true);
889      }
890  
891      /**
# Line 944 | Line 896 | public class TreeMap<K,V>
896       * @throws IllegalArgumentException {@inheritDoc}
897       */
898      public SortedMap<K,V> subMap(K fromKey, K toKey) {
899 <        return navigableSubMap(fromKey, true, toKey, false);
899 >        return subMap(fromKey, true, toKey, false);
900      }
901  
902      /**
# Line 955 | Line 907 | public class TreeMap<K,V>
907       * @throws IllegalArgumentException {@inheritDoc}
908       */
909      public SortedMap<K,V> headMap(K toKey) {
910 <        return navigableHeadMap(toKey, false);
910 >        return headMap(toKey, false);
911      }
912  
913      /**
# Line 966 | Line 918 | public class TreeMap<K,V>
918       * @throws IllegalArgumentException {@inheritDoc}
919       */
920      public SortedMap<K,V> tailMap(K fromKey) {
921 <        return navigableTailMap(fromKey, true);
921 >        return tailMap(fromKey, true);
922      }
923  
924      // View class support
# Line 981 | Line 933 | public class TreeMap<K,V>
933          }
934  
935          public boolean contains(Object o) {
936 <            for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
985 <                if (valEquals(e.getValue(), o))
986 <                    return true;
987 <            return false;
936 >            return TreeMap.this.containsValue(o);
937          }
938  
939          public boolean remove(Object o) {
# Line 1096 | Line 1045 | public class TreeMap<K,V>
1045              m.remove(o);
1046              return size() != oldSize;
1047          }
1048 <        public NavigableSet<E> navigableSubSet(E fromElement,
1049 <                                               boolean fromInclusive,
1050 <                                               E toElement,  
1051 <                                               boolean toInclusive) {
1103 <            return new TreeSet<E>
1104 <                (m.navigableSubMap(fromElement, fromInclusive,
1105 <                                   toElement,   toInclusive));
1048 >        public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
1049 >                                      E toElement, boolean toInclusive) {
1050 >            return new TreeSet<E>(m.subMap(fromElement, fromInclusive,
1051 >                                           toElement,   toInclusive));
1052          }
1053 <        public NavigableSet<E> navigableHeadSet(E toElement, boolean inclusive) {
1054 <            return new TreeSet<E>(m.navigableHeadMap(toElement, inclusive));
1053 >        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1054 >            return new TreeSet<E>(m.headMap(toElement, inclusive));
1055          }
1056 <        public NavigableSet<E> navigableTailSet(E fromElement, boolean inclusive) {
1057 <            return new TreeSet<E>(m.navigableTailMap(fromElement, inclusive));
1056 >        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1057 >            return new TreeSet<E>(m.tailMap(fromElement, inclusive));
1058          }
1059          public SortedSet<E> subSet(E fromElement, E toElement) {
1060 <            return navigableSubSet(fromElement, true, toElement, false);
1060 >            return subSet(fromElement, true, toElement, false);
1061          }
1062          public SortedSet<E> headSet(E toElement) {
1063 <            return navigableHeadSet(toElement, false);
1063 >            return headSet(toElement, false);
1064          }
1065          public SortedSet<E> tailSet(E fromElement) {
1066 <            return navigableTailSet(fromElement, true);
1066 >            return tailSet(fromElement, true);
1067          }
1068          public NavigableSet<E> descendingSet() {
1069              return new TreeSet(m.descendingMap());
1070          }
1071      }
1072  
1073 <    // SubMaps
1074 <
1075 <    abstract class NavigableSubMap extends AbstractMap<K,V>
1076 <        implements NavigableMap<K,V>, java.io.Serializable {
1077 <
1078 <        /**
1079 <         * The low endpoint of this submap in absolute terms.  For ascending
1134 <         * submaps this will be the "first" endpoint; for descending submaps,
1135 <         * the last.  If there is no bound, this field is set to UNBOUNDED.
1136 <         */
1137 <        K lo;
1138 <
1139 <        /**
1140 <         * Zero if the low endpoint is excluded from this submap, one if
1141 <         * it's included.  This field is unused if lo is UNBOUNDED.
1142 <         */
1143 <        int loExcluded;
1144 <
1145 <        /**
1146 <         * The high endpoint of this submap in absolute terms.  For ascending
1147 <         * submaps this will be the "last" endpoint; for descending submaps,
1148 <         * the first.  If there is no bound, this field is set to UNBOUNDED.
1149 <         */
1150 <        K hi;
1151 <
1152 <        /**
1153 <         * Zero if the high endpoint is excluded from this submap, one if
1154 <         * it's included.  This field is unused if hi is UNBOUNDED.
1155 <         */
1156 <        int hiExcluded;
1073 >    /**
1074 >     * Base class for TreeMap Iterators
1075 >     */
1076 >    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1077 >        Entry<K,V> next;
1078 >        Entry<K,V> lastReturned;
1079 >        int expectedModCount;
1080  
1081 <        NavigableSubMap(K lo, int loExcluded, K hi, int hiExcluded) {
1082 <            if (lo != UNBOUNDED && hi != UNBOUNDED && compare(lo, hi) > 0)
1083 <                throw new IllegalArgumentException("fromKey > toKey");
1084 <            this.lo = lo;
1162 <            this.loExcluded = loExcluded;
1163 <            this.hi = hi;
1164 <            this.hiExcluded = hiExcluded;
1081 >        PrivateEntryIterator(Entry<K,V> first) {
1082 >            expectedModCount = modCount;
1083 >            lastReturned = null;
1084 >            next = first;
1085          }
1086  
1087 <        public boolean isEmpty() {
1088 <            return entrySet().isEmpty();
1087 >        public final boolean hasNext() {
1088 >            return next != null;
1089          }
1090  
1091 <        public boolean containsKey(Object key) {
1092 <            return inRange(key) && TreeMap.this.containsKey(key);
1091 >        final Entry<K,V> nextEntry() {
1092 >            Entry<K,V> e = lastReturned = next;
1093 >            if (e == null)
1094 >                throw new NoSuchElementException();
1095 >            if (modCount != expectedModCount)
1096 >                throw new ConcurrentModificationException();
1097 >            next = successor(e);
1098 >            return e;
1099          }
1100  
1101 <        public V get(Object key) {
1102 <            if (!inRange(key))
1103 <                return null;
1104 <            return TreeMap.this.get(key);
1101 >        final Entry<K,V> prevEntry() {
1102 >            Entry<K,V> e = lastReturned= next;
1103 >            if (e == null)
1104 >                throw new NoSuchElementException();
1105 >            if (modCount != expectedModCount)
1106 >                throw new ConcurrentModificationException();
1107 >            next = predecessor(e);
1108 >            return e;
1109          }
1110  
1111 <        public V put(K key, V value) {
1112 <            if (!inRange(key))
1113 <                throw new IllegalArgumentException("key out of range");
1114 <            return TreeMap.this.put(key, value);
1111 >        public void remove() {
1112 >            if (lastReturned == null)
1113 >                throw new IllegalStateException();
1114 >            if (modCount != expectedModCount)
1115 >                throw new ConcurrentModificationException();
1116 >            if (lastReturned.left != null && lastReturned.right != null)
1117 >                next = lastReturned;
1118 >            deleteEntry(lastReturned);
1119 >            expectedModCount++;
1120 >            lastReturned = null;
1121          }
1122 +    }
1123  
1124 <        public V remove(Object key) {
1125 <            if (!inRange(key))
1126 <                return null;
1190 <            return TreeMap.this.remove(key);
1124 >    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1125 >        EntryIterator(Entry<K,V> first) {
1126 >            super(first);
1127          }
1128 <
1129 <        public Map.Entry<K,V> ceilingEntry(K key) {
1194 <            TreeMap.Entry<K,V> e = subCeiling(key);
1195 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1128 >        public Map.Entry<K,V> next() {
1129 >            return nextEntry();
1130          }
1131 +    }
1132  
1133 <        public K ceilingKey(K key) {
1134 <            TreeMap.Entry<K,V> e = subCeiling(key);
1135 <            return e == null? null : e.key;
1133 >    final class ValueIterator extends PrivateEntryIterator<V> {
1134 >        ValueIterator(Entry<K,V> first) {
1135 >            super(first);
1136          }
1137 <
1138 <        public Map.Entry<K,V> higherEntry(K key) {
1204 <            TreeMap.Entry<K,V> e = subHigher(key);
1205 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1137 >        public V next() {
1138 >            return nextEntry().value;
1139          }
1140 +    }
1141  
1142 <        public K higherKey(K key) {
1143 <            TreeMap.Entry<K,V> e = subHigher(key);
1144 <            return e == null? null : e.key;
1142 >    final class KeyIterator extends PrivateEntryIterator<K> {
1143 >        KeyIterator(Entry<K,V> first) {
1144 >            super(first);
1145          }
1146 <
1147 <        public Map.Entry<K,V> floorEntry(K key) {
1214 <            TreeMap.Entry<K,V> e = subFloor(key);
1215 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1146 >        public K next() {
1147 >            return nextEntry().key;
1148          }
1149 +    }
1150  
1151 <        public K floorKey(K key) {
1152 <            TreeMap.Entry<K,V> e = subFloor(key);
1153 <            return e == null? null : e.key;
1151 >    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1152 >        DescendingKeyIterator(Entry<K,V> first) {
1153 >            super(first);
1154          }
1155 <
1156 <        public Map.Entry<K,V> lowerEntry(K key) {
1224 <            TreeMap.Entry<K,V> e = subLower(key);
1225 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1155 >        public K next() {
1156 >            return prevEntry().key;
1157          }
1158 +    }
1159  
1160 <        public K lowerKey(K key) {
1229 <            TreeMap.Entry<K,V> e = subLower(key);
1230 <            return e == null? null : e.key;
1231 <        }
1160 >    // Little utilities
1161  
1162 <        abstract Iterator<K> keyIterator();
1163 <        abstract Iterator<K> descendingKeyIterator();
1162 >    /**
1163 >     * Compares two keys using the correct comparison method for this TreeMap.
1164 >     */
1165 >    final int compare(Object k1, Object k2) {
1166 >        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1167 >            : comparator.compare((K)k1, (K)k2);
1168 >    }
1169  
1170 <        public NavigableSet<K> descendingKeySet() {
1171 <            return descendingMap().navigableKeySet();
1172 <        }
1170 >    /**
1171 >     * Test two values for equality.  Differs from o1.equals(o2) only in
1172 >     * that it copes with <tt>null</tt> o1 properly.
1173 >     */
1174 >    final static boolean valEquals(Object o1, Object o2) {
1175 >        return (o1==null ? o2==null : o1.equals(o2));
1176 >    }
1177  
1178 <        // Views
1179 <        transient NavigableMap<K,V> descendingMapView = null;
1180 <        transient Set<Map.Entry<K,V>> entrySetView = null;
1181 <        private transient NavigableSet<K> navigableKeySetView = null;
1178 >    /**
1179 >     * Return SimpleImmutableEntry for entry, or null if null
1180 >     */
1181 >    static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
1182 >        return e == null? null :
1183 >            new AbstractMap.SimpleImmutableEntry<K,V>(e);
1184 >    }
1185  
1186 <        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1187 <            private transient int size = -1, sizeModCount;
1186 >    /**
1187 >     * Return key for entry, or null if null
1188 >     */
1189 >    static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
1190 >        return e == null? null : e.key;
1191 >    }
1192  
1193 <            public int size() {
1194 <                if (size == -1 || sizeModCount != TreeMap.this.modCount) {
1195 <                    size = 0;  sizeModCount = TreeMap.this.modCount;
1196 <                    Iterator i = iterator();
1197 <                    while (i.hasNext()) {
1198 <                        size++;
1199 <                        i.next();
1200 <                    }
1201 <                }
1257 <                return size;
1258 <            }
1193 >    /**
1194 >     * Returns the key corresponding to the specified Entry.
1195 >     * @throws NoSuchElementException if the Entry is null
1196 >     */
1197 >    static <K> K key(Entry<K,?> e) {
1198 >        if (e==null)
1199 >            throw new NoSuchElementException();
1200 >        return e.key;
1201 >    }
1202  
1260            public boolean isEmpty() {
1261                return !iterator().hasNext();
1262            }
1203  
1204 <            public boolean contains(Object o) {
1265 <                if (!(o instanceof Map.Entry))
1266 <                    return false;
1267 <                Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1268 <                K key = entry.getKey();
1269 <                if (!inRange(key))
1270 <                    return false;
1271 <                TreeMap.Entry node = getEntry(key);
1272 <                return node != null &&
1273 <                       valEquals(node.getValue(), entry.getValue());
1274 <            }
1204 >    // SubMaps
1205  
1206 <            public boolean remove(Object o) {
1207 <                if (!(o instanceof Map.Entry))
1208 <                    return false;
1209 <                Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1210 <                K key = entry.getKey();
1211 <                if (!inRange(key))
1212 <                    return false;
1213 <                TreeMap.Entry<K,V> node = getEntry(key);
1214 <                if (node!=null && valEquals(node.getValue(),entry.getValue())){
1215 <                    deleteEntry(node);
1216 <                    return true;
1217 <                }
1218 <                return false;
1206 >    static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
1207 >        implements NavigableMap<K,V>, java.io.Serializable {
1208 >        /*
1209 >         * The backing map.
1210 >         */
1211 >        final TreeMap<K,V> m;
1212 >
1213 >        /*
1214 >         * Endpoints are represented as triples (fromStart, lo,
1215 >         * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is
1216 >         * true, then the low (absolute) bound is the start of the
1217 >         * backing map, and the other values are ignored. Otherwise,
1218 >         * if loInclusive is true, lo is the inclusive bound, else lo
1219 >         * is the exclusive bound. Similarly for the upper bound.
1220 >         */
1221 >
1222 >        final K lo, hi;
1223 >        final boolean fromStart, toEnd;
1224 >        final boolean loInclusive, hiInclusive;
1225 >
1226 >        NavigableSubMap(TreeMap<K,V> m,
1227 >                        boolean fromStart, K lo, boolean loInclusive,
1228 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1229 >            if (!fromStart && !toEnd) {
1230 >                if (m.compare(lo, hi) > 0)
1231 >                    throw new IllegalArgumentException("fromKey > toKey");
1232 >            } else {
1233 >                if (!fromStart) // type check
1234 >                    m.compare(lo, lo);
1235 >                if (!toEnd)
1236 >                    m.compare(hi, hi);
1237              }
1290        }
1238  
1239 <        public NavigableSet<K> navigableKeySet() {
1240 <            NavigableSet<K> nksv = navigableKeySetView;
1241 <            return (nksv != null) ? nksv :
1242 <                (navigableKeySetView = new TreeMap.KeySet(this));
1239 >            this.m = m;
1240 >            this.fromStart = fromStart;
1241 >            this.lo = lo;
1242 >            this.loInclusive = loInclusive;
1243 >            this.toEnd = toEnd;
1244 >            this.hi = hi;
1245 >            this.hiInclusive = hiInclusive;
1246          }
1247  
1248 <        public Set<K> keySet() {
1299 <            return navigableKeySet();
1300 <        }
1248 >        // internal utilities
1249  
1250 <        public SortedMap<K,V> subMap(K fromKey, K toKey) {
1251 <            return navigableSubMap(fromKey, true, toKey, false);
1250 >        final boolean tooLow(Object key) {
1251 >            if (!fromStart) {
1252 >                int c = m.compare(key, lo);
1253 >                if (c < 0 || (c == 0 && !loInclusive))
1254 >                    return true;
1255 >            }
1256 >            return false;
1257          }
1258  
1259 <        public SortedMap<K,V> headMap(K toKey) {
1260 <            return navigableHeadMap(toKey, false);
1259 >        final boolean tooHigh(Object key) {
1260 >            if (!toEnd) {
1261 >                int c = m.compare(key, hi);
1262 >                if (c > 0 || (c == 0 && !hiInclusive))
1263 >                    return true;
1264 >            }
1265 >            return false;
1266          }
1267  
1268 <        public SortedMap<K,V> tailMap(K fromKey) {
1269 <            return navigableTailMap(fromKey, true);
1268 >        final boolean inRange(Object key) {
1269 >            return !tooLow(key) && !tooHigh(key);
1270          }
1271  
1272 <        /** Returns the lowest entry in this submap (absolute ordering) */
1273 <        TreeMap.Entry<K,V> loEntry() {
1274 <            TreeMap.Entry<K,V> result =
1317 <                ((lo == UNBOUNDED) ? getFirstEntry() :
1318 <                 (loExcluded == 0) ? getCeilingEntry(lo) : getHigherEntry(lo));
1319 <            return (result == null || tooHigh(result.key)) ? null : result;
1272 >        final boolean inClosedRange(Object key) {
1273 >            return (fromStart || m.compare(key, lo) >= 0)
1274 >                && (toEnd || m.compare(hi, key) >= 0);
1275          }
1276  
1277 <        /** Returns the highest key in this submap (absolute ordering) */
1278 <        TreeMap.Entry<K,V> hiEntry() {
1324 <            TreeMap.Entry<K,V> result =
1325 <                ((hi == UNBOUNDED) ? getLastEntry() :
1326 <                 (hiExcluded == 0) ? getFloorEntry(hi) : getLowerEntry(hi));
1327 <            return (result == null || tooLow(result.key)) ? null : result;
1277 >        final boolean inRange(Object key, boolean inclusive) {
1278 >            return inclusive ? inRange(key) : inClosedRange(key);
1279          }
1280  
1281 <        /** Polls the lowest entry in this submap (absolute ordering) */
1282 <        Map.Entry<K,V> pollLoEntry() {
1281 >        /*
1282 >         * Absolute versions of relation operations.
1283 >         * Subclasses map to these using like-named "sub"
1284 >         * versions that invert senses for descending maps
1285 >         */
1286 >
1287 >        final TreeMap.Entry<K,V> absLowest() {
1288              TreeMap.Entry<K,V> e =
1289 <                ((lo == UNBOUNDED) ? getFirstEntry() :
1290 <                 (loExcluded == 0) ? getCeilingEntry(lo) : getHigherEntry(lo));
1291 <            if (e == null || tooHigh(e.key))
1292 <                return null;
1337 <            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1338 <            deleteEntry(e);
1339 <            return result;            
1289 >                (fromStart ?  m.getFirstEntry() :
1290 >                 (loInclusive ? m.getCeilingEntry(lo) :
1291 >                                m.getHigherEntry(lo)));
1292 >            return (e == null || tooHigh(e.key)) ? null : e;
1293          }
1294  
1295 <        /** Polls the highest key in this submap (absolute ordering) */
1343 <        Map.Entry<K,V> pollHiEntry() {
1295 >        final TreeMap.Entry<K,V> absHighest() {
1296              TreeMap.Entry<K,V> e =
1297 <                ((hi == UNBOUNDED) ? getLastEntry() :
1298 <                 (hiExcluded == 0) ? getFloorEntry(hi) : getLowerEntry(hi));
1299 <            if (e == null || tooLow(e.key))
1300 <                return null;
1349 <            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1350 <            deleteEntry(e);
1351 <            return result;            
1297 >                (toEnd ?  m.getLastEntry() :
1298 >                 (hiInclusive ?  m.getFloorEntry(hi) :
1299 >                                 m.getLowerEntry(hi)));
1300 >            return (e == null || tooLow(e.key)) ? null : e;
1301          }
1302  
1303 <        // The following four definitions are correct only for
1355 <        // ascending submaps. They are overridden in DescendingSubMap.
1356 <        // They are defined in the base class because the definitions
1357 <        // in DescendingSubMap rely on those for AscendingSubMap.
1358 <
1359 <        /**
1360 <         * Returns the entry corresponding to the ceiling of the specified
1361 <         * key from the perspective of this submap, or null if the submap
1362 <         * contains no such entry.
1363 <         */
1364 <        TreeMap.Entry<K,V> subCeiling(K key) {
1303 >        final TreeMap.Entry<K,V> absCeiling(K key) {
1304              if (tooLow(key))
1305 <                return loEntry();
1306 <            TreeMap.Entry<K,V> e = getCeilingEntry(key);
1305 >                return absLowest();
1306 >            TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
1307              return (e == null || tooHigh(e.key)) ? null : e;
1308          }
1309  
1310 <        /**
1372 <         * Returns the entry corresponding to the higher of the specified
1373 <         * key from the perspective of this submap, or null if the submap
1374 <         * contains no such entry.
1375 <         */
1376 <        TreeMap.Entry<K,V> subHigher(K key) {
1310 >        final TreeMap.Entry<K,V> absHigher(K key) {
1311              if (tooLow(key))
1312 <                return loEntry();
1313 <            TreeMap.Entry<K,V> e = getHigherEntry(key);
1312 >                return absLowest();
1313 >            TreeMap.Entry<K,V> e = m.getHigherEntry(key);
1314              return (e == null || tooHigh(e.key)) ? null : e;
1315          }
1316  
1317 <        /**
1384 <         * Returns the entry corresponding to the floor of the specified
1385 <         * key from the perspective of this submap, or null if the submap
1386 <         * contains no such entry.
1387 <         */
1388 <        TreeMap.Entry<K,V> subFloor(K key) {
1317 >        final TreeMap.Entry<K,V> absFloor(K key) {
1318              if (tooHigh(key))
1319 <                return hiEntry();
1320 <            TreeMap.Entry<K,V> e = getFloorEntry(key);
1319 >                return absHighest();
1320 >            TreeMap.Entry<K,V> e = m.getFloorEntry(key);
1321              return (e == null || tooLow(e.key)) ? null : e;
1322          }
1323  
1324 <        /**
1396 <         * Returns the entry corresponding to the lower of the specified
1397 <         * key from the perspective of this submap, or null if the submap
1398 <         * contains no such entry.
1399 <         */
1400 <        TreeMap.Entry<K,V> subLower(K key) {
1324 >        final TreeMap.Entry<K,V> absLower(K key) {
1325              if (tooHigh(key))
1326 <                return hiEntry();
1327 <            TreeMap.Entry<K,V> e = getLowerEntry(key);
1326 >                return absHighest();
1327 >            TreeMap.Entry<K,V> e = m.getLowerEntry(key);
1328              return (e == null || tooLow(e.key)) ? null : e;
1329          }
1330  
1331 <        boolean inRange(Object key) {
1332 <            return (lo == UNBOUNDED || compare(key, lo) >= loExcluded)
1333 <                && (hi == UNBOUNDED || compare(hi, key) >= hiExcluded);
1334 <        }
1331 >        /** Returns the absolute high fence for ascending traversal */
1332 >        final TreeMap.Entry<K,V> absHighFence() {
1333 >            return (toEnd ? null : (hiInclusive ?
1334 >                                    m.getHigherEntry(hi) :
1335 >                                    m.getCeilingEntry(hi)));
1336 >        }
1337 >
1338 >        /** Return the absolute low fence for descending traversal  */
1339 >        final TreeMap.Entry<K,V> absLowFence() {
1340 >            return (fromStart ? null : (loInclusive ?
1341 >                                        m.getLowerEntry(lo) :
1342 >                                        m.getFloorEntry(lo)));
1343 >        }
1344 >
1345 >        // Abstract methods defined in ascending vs descending classes
1346 >        // These relay to the appropriate  absolute versions
1347 >
1348 >        abstract TreeMap.Entry<K,V> subLowest();
1349 >        abstract TreeMap.Entry<K,V> subHighest();
1350 >        abstract TreeMap.Entry<K,V> subCeiling(K key);
1351 >        abstract TreeMap.Entry<K,V> subHigher(K key);
1352 >        abstract TreeMap.Entry<K,V> subFloor(K key);
1353 >        abstract TreeMap.Entry<K,V> subLower(K key);
1354  
1355 <        boolean inClosedRange(Object key) {
1356 <            return (lo == UNBOUNDED || compare(key, lo) >= 0)
1414 <                && (hi == UNBOUNDED || compare(hi, key) >= 0);
1415 <        }
1355 >        /** Returns ascending iterator from the perspective of this submap */
1356 >        abstract Iterator<K> keyIterator();
1357  
1358 <        boolean inRange(Object key, boolean inclusive) {
1359 <            return inclusive ? inRange(key) : inClosedRange(key);
1358 >        /** Returns descending iterator from the perspective of this submap */
1359 >        abstract Iterator<K> descendingKeyIterator();
1360 >
1361 >        // public methods
1362 >
1363 >        public boolean isEmpty() {
1364 >            return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1365          }
1366  
1367 <        boolean tooLow(K key) {
1368 <            return lo != UNBOUNDED && compare(key, lo) < loExcluded;
1367 >        public int size() {
1368 >            return (fromStart && toEnd) ? m.size() : entrySet().size();
1369          }
1370  
1371 <        boolean tooHigh(K key) {
1372 <            return hi != UNBOUNDED && compare(hi, key) < hiExcluded;
1371 >        public final boolean containsKey(Object key) {
1372 >            return inRange(key) && m.containsKey(key);
1373          }
1428    }
1374  
1375 <    class AscendingSubMap extends NavigableSubMap {
1376 <        private static final long serialVersionUID = 912986545866124060L;
1375 >        public final V put(K key, V value) {
1376 >            if (!inRange(key))
1377 >                throw new IllegalArgumentException("key out of range");
1378 >            return m.put(key, value);
1379 >        }
1380  
1381 <        AscendingSubMap(K lo, int loExcluded, K hi, int hiExcluded) {
1382 <            super(lo, loExcluded, hi, hiExcluded);
1381 >        public final V get(Object key) {
1382 >            return !inRange(key)? null :  m.get(key);
1383          }
1384  
1385 <        public Comparator<? super K> comparator() {
1386 <            return comparator;
1385 >        public final V remove(Object key) {
1386 >            return !inRange(key)? null  : m.remove(key);
1387          }
1388  
1389 <        public NavigableMap<K,V> navigableSubMap(
1390 <              K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
1443 <            if (!inRange(fromKey, fromInclusive))
1444 <                throw new IllegalArgumentException("fromKey out of range");
1445 <            if (!inRange(toKey, toInclusive))
1446 <                throw new IllegalArgumentException("toKey out of range");
1447 <            return new AscendingSubMap(fromKey, excluded(fromInclusive),
1448 <                                       toKey,   excluded(toInclusive));
1389 >        public final Map.Entry<K,V> ceilingEntry(K key) {
1390 >            return exportEntry(subCeiling(key));
1391          }
1392  
1393 <        public NavigableMap<K,V> navigableHeadMap(K toKey, boolean inclusive) {
1394 <            if (!inClosedRange(toKey))
1453 <                throw new IllegalArgumentException("toKey out of range");
1454 <            return new AscendingSubMap(lo,    loExcluded,
1455 <                                       toKey, excluded(inclusive));
1393 >        public final K ceilingKey(K key) {
1394 >            return keyOrNull(subCeiling(key));
1395          }
1396  
1397 <        public NavigableMap<K,V> navigableTailMap(K fromKey, boolean inclusive){
1398 <            if (!inRange(fromKey, inclusive))
1460 <                throw new IllegalArgumentException("fromKey out of range");
1461 <            return new AscendingSubMap(fromKey, excluded(inclusive),
1462 <                                       hi,      hiExcluded);
1397 >        public final Map.Entry<K,V> higherEntry(K key) {
1398 >            return exportEntry(subHigher(key));
1399          }
1400  
1401 <        Iterator<K> keyIterator() {
1402 <            return new SubMapKeyIterator
1467 <                (loEntry(),
1468 <                 hi == UNBOUNDED ? null :
1469 <                 hiExcluded == 1 ? getCeilingEntry(hi) :
1470 <                 getHigherEntry(hi));
1401 >        public final K higherKey(K key) {
1402 >            return keyOrNull(subHigher(key));
1403          }
1404  
1405 <        Iterator<K> descendingKeyIterator() {
1406 <            return new DescendingSubMapKeyIterator
1475 <                (hiEntry(),
1476 <                 lo == UNBOUNDED ? null :
1477 <                 loExcluded == 1 ? getFloorEntry(lo) :
1478 <                 getLowerEntry(lo));
1405 >        public final Map.Entry<K,V> floorEntry(K key) {
1406 >            return exportEntry(subFloor(key));
1407          }
1408  
1409 <        public Set<Map.Entry<K,V>> entrySet() {
1410 <            Set<Map.Entry<K,V>> es = entrySetView;
1483 <            if  (es != null)
1484 <                return es;
1485 <            return entrySetView = new NavigableSubMap.EntrySetView() {
1486 <                public Iterator<Map.Entry<K,V>> iterator() {
1487 <                    return new SubMapEntryIterator(loEntry(),
1488 <                        hi == UNBOUNDED ? null :
1489 <                        hiExcluded == 1 ? getCeilingEntry(hi) :
1490 <                        getHigherEntry(hi));
1491 <                }
1492 <            };
1409 >        public final K floorKey(K key) {
1410 >            return keyOrNull(subFloor(key));
1411          }
1412  
1413 <        public K firstKey() {
1414 <            return key(loEntry());
1413 >        public final Map.Entry<K,V> lowerEntry(K key) {
1414 >            return exportEntry(subLower(key));
1415          }
1416  
1417 <        public K lastKey() {
1418 <            return key(hiEntry());
1417 >        public final K lowerKey(K key) {
1418 >            return keyOrNull(subLower(key));
1419          }
1420  
1421 <        public Map.Entry<K,V> firstEntry() {
1422 <            return loEntry();
1421 >        public final K firstKey() {
1422 >            return key(subLowest());
1423          }
1424  
1425 <        public Map.Entry<K,V> lastEntry() {
1426 <            return hiEntry();
1425 >        public final K lastKey() {
1426 >            return key(subHighest());
1427          }
1428  
1429 <        public Map.Entry<K,V> pollFirstEntry() {
1430 <            return pollLoEntry();
1429 >        public final Map.Entry<K,V> firstEntry() {
1430 >            return exportEntry(subLowest());
1431          }
1432  
1433 <        public Map.Entry<K,V> pollLastEntry() {
1434 <            return pollHiEntry();
1433 >        public final Map.Entry<K,V> lastEntry() {
1434 >            return exportEntry(subHighest());
1435          }
1436  
1437 <        public NavigableMap<K,V> descendingMap() {
1438 <            NavigableMap<K,V> m = descendingMapView;
1439 <            return (m != null) ? m :
1440 <                (descendingMapView =
1441 <                 new DescendingSubMap(lo, loExcluded, hi, hiExcluded));
1437 >        public final Map.Entry<K,V> pollFirstEntry() {
1438 >            TreeMap.Entry<K,V> e = subLowest();
1439 >            Map.Entry<K,V> result = exportEntry(e);
1440 >            if (e != null)
1441 >                m.deleteEntry(e);
1442 >            return result;
1443          }
1525    }
1444  
1445 <    class DescendingSubMap extends NavigableSubMap {
1446 <        private static final long serialVersionUID = 912986545866120460L;
1447 <        DescendingSubMap(K lo, int loExcluded, K hi, int hiExcluded) {
1448 <            super(lo, loExcluded, hi, hiExcluded);
1445 >        public final Map.Entry<K,V> pollLastEntry() {
1446 >            TreeMap.Entry<K,V> e = subHighest();
1447 >            Map.Entry<K,V> result = exportEntry(e);
1448 >            if (e != null)
1449 >                m.deleteEntry(e);
1450 >            return result;
1451          }
1452  
1453 <        private final Comparator<? super K> reverseComparator =
1454 <            Collections.reverseOrder(comparator);
1453 >        // Views
1454 >        transient NavigableMap<K,V> descendingMapView = null;
1455 >        transient EntrySetView entrySetView = null;
1456 >        transient KeySet<K> navigableKeySetView = null;
1457  
1458 <        public Comparator<? super K> comparator() {
1459 <            return reverseComparator;
1458 >        public final NavigableSet<K> navigableKeySet() {
1459 >            KeySet<K> nksv = navigableKeySetView;
1460 >            return (nksv != null) ? nksv :
1461 >                (navigableKeySetView = new TreeMap.KeySet(this));
1462          }
1463  
1464 <        public NavigableMap<K,V> navigableSubMap(
1465 <              K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
1542 <            if (!inRange(fromKey, fromInclusive))
1543 <                throw new IllegalArgumentException("fromKey out of range");
1544 <            if (!inRange(toKey, toInclusive))
1545 <                throw new IllegalArgumentException("toKey out of range");
1546 <            return new DescendingSubMap(toKey,   excluded(toInclusive),
1547 <                                        fromKey, excluded(fromInclusive));
1464 >        public final Set<K> keySet() {
1465 >            return navigableKeySet();
1466          }
1467  
1468 <        public NavigableMap<K,V> navigableHeadMap(K toKey, boolean inclusive) {
1469 <            if (!inRange(toKey, inclusive))
1552 <                throw new IllegalArgumentException("toKey out of range");
1553 <            return new DescendingSubMap(toKey, inclusive ? 0:1, hi, hiExcluded);
1468 >        public NavigableSet<K> descendingKeySet() {
1469 >            return descendingMap().navigableKeySet();
1470          }
1471  
1472 <        public NavigableMap<K,V> navigableTailMap(K fromKey, boolean inclusive){
1473 <            if (!inRange(fromKey, inclusive))
1558 <                throw new IllegalArgumentException("fromKey out of range");
1559 <            return new DescendingSubMap(lo,      loExcluded,
1560 <                                        fromKey, excluded(inclusive));
1472 >        public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1473 >            return subMap(fromKey, true, toKey, false);
1474          }
1475  
1476 <        Iterator<K> keyIterator() {
1477 <            return new DescendingSubMapKeyIterator
1565 <                (hiEntry(),
1566 <                 lo == UNBOUNDED ? null :
1567 <                 loExcluded == 1 ? getFloorEntry(lo) :
1568 <                 getLowerEntry(lo));
1476 >        public final SortedMap<K,V> headMap(K toKey) {
1477 >            return headMap(toKey, false);
1478          }
1479  
1480 <        Iterator<K> descendingKeyIterator() {
1481 <            return new SubMapKeyIterator
1573 <                (loEntry(),
1574 <                 hi == UNBOUNDED ? null :
1575 <                 hiExcluded == 1 ? getCeilingEntry(hi) :
1576 <                 getHigherEntry(hi));
1480 >        public final SortedMap<K,V> tailMap(K fromKey) {
1481 >            return tailMap(fromKey, true);
1482          }
1483  
1484 <        public Set<Map.Entry<K,V>> entrySet() {
1485 <            Set<Map.Entry<K,V>> es = entrySetView;
1486 <            if  (es != null)
1487 <                return es;
1488 <            return entrySetView = new NavigableSubMap.EntrySetView() {
1489 <                public Iterator<Map.Entry<K,V>> iterator() {
1490 <                    return new DescendingSubMapEntryIterator(hiEntry(),
1491 <                        lo == UNBOUNDED ? null :
1492 <                        loExcluded == 1 ? getFloorEntry(lo) :
1493 <                        getLowerEntry(lo));
1484 >        // View classes
1485 >
1486 >        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1487 >            private transient int size = -1, sizeModCount;
1488 >
1489 >            public int size() {
1490 >                if (fromStart && toEnd)
1491 >                    return m.size();
1492 >                if (size == -1 || sizeModCount != m.modCount) {
1493 >                    sizeModCount = m.modCount;
1494 >                    size = 0;
1495 >                    Iterator i = iterator();
1496 >                    while (i.hasNext()) {
1497 >                        size++;
1498 >                        i.next();
1499 >                    }
1500                  }
1501 <            };
1502 <        }
1501 >                return size;
1502 >            }
1503  
1504 <        public K firstKey() {
1505 <            return key(hiEntry());
1506 <        }
1504 >            public boolean isEmpty() {
1505 >                TreeMap.Entry<K,V> n = absLowest();
1506 >                return n == null || tooHigh(n.key);
1507 >            }
1508  
1509 <        public K lastKey() {
1510 <            return key(loEntry());
1511 <        }
1509 >            public boolean contains(Object o) {
1510 >                if (!(o instanceof Map.Entry))
1511 >                    return false;
1512 >                Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1513 >                K key = entry.getKey();
1514 >                if (!inRange(key))
1515 >                    return false;
1516 >                TreeMap.Entry node = m.getEntry(key);
1517 >                return node != null &&
1518 >                    valEquals(node.getValue(), entry.getValue());
1519 >            }
1520  
1521 <        public Map.Entry<K,V> firstEntry() {
1522 <            return hiEntry();
1521 >            public boolean remove(Object o) {
1522 >                if (!(o instanceof Map.Entry))
1523 >                    return false;
1524 >                Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
1525 >                K key = entry.getKey();
1526 >                if (!inRange(key))
1527 >                    return false;
1528 >                TreeMap.Entry<K,V> node = m.getEntry(key);
1529 >                if (node!=null && valEquals(node.getValue(),entry.getValue())){
1530 >                    m.deleteEntry(node);
1531 >                    return true;
1532 >                }
1533 >                return false;
1534 >            }
1535          }
1536  
1537 <        public Map.Entry<K,V> lastEntry() {
1538 <            return loEntry();
1539 <        }
1537 >        /**
1538 >         * Iterators for SubMaps
1539 >         */
1540 >        abstract class SubMapIterator<T> implements Iterator<T> {
1541 >            TreeMap.Entry<K,V> lastReturned;
1542 >            TreeMap.Entry<K,V> next;
1543 >            final K fenceKey;
1544 >            int expectedModCount;
1545 >
1546 >            SubMapIterator(TreeMap.Entry<K,V> first,
1547 >                           TreeMap.Entry<K,V> fence) {
1548 >                expectedModCount = m.modCount;
1549 >                lastReturned = null;
1550 >                next = first;
1551 >                fenceKey = fence == null ? null : fence.key;
1552 >            }
1553  
1554 <        public Map.Entry<K,V> pollFirstEntry() {
1555 <            return pollHiEntry();
1556 <        }
1554 >            public final boolean hasNext() {
1555 >                return next != null && next.key != fenceKey;
1556 >            }
1557  
1558 <        public Map.Entry<K,V> pollLastEntry() {
1559 <            return pollLoEntry();
1560 <        }
1558 >            final TreeMap.Entry<K,V> nextEntry() {
1559 >                TreeMap.Entry<K,V> e = lastReturned = next;
1560 >                if (e == null || e.key == fenceKey)
1561 >                    throw new NoSuchElementException();
1562 >                if (m.modCount != expectedModCount)
1563 >                    throw new ConcurrentModificationException();
1564 >                next = successor(e);
1565 >                return e;
1566 >            }
1567  
1568 <        public NavigableMap<K,V> descendingMap() {
1569 <            NavigableMap<K,V> m = descendingMapView;
1570 <            return (m != null) ? m :
1571 <                (descendingMapView =
1572 <                 new AscendingSubMap(lo, loExcluded, hi, hiExcluded));
1573 <        }
1568 >            final TreeMap.Entry<K,V> prevEntry() {
1569 >                TreeMap.Entry<K,V> e = lastReturned = next;
1570 >                if (e == null || e.key == fenceKey)
1571 >                    throw new NoSuchElementException();
1572 >                if (m.modCount != expectedModCount)
1573 >                    throw new ConcurrentModificationException();
1574 >                next = predecessor(e);
1575 >                return e;
1576 >            }
1577  
1578 <        @Override TreeMap.Entry<K,V> subCeiling(K key) {
1579 <            return super.subFloor(key);
1578 >            public void remove() {
1579 >                if (lastReturned == null)
1580 >                    throw new IllegalStateException();
1581 >                if (m.modCount != expectedModCount)
1582 >                    throw new ConcurrentModificationException();
1583 >                if (lastReturned.left != null && lastReturned.right != null)
1584 >                    next = lastReturned;
1585 >                m.deleteEntry(lastReturned);
1586 >                expectedModCount++;
1587 >                lastReturned = null;
1588 >            }
1589          }
1590  
1591 <        @Override TreeMap.Entry<K,V> subHigher(K key) {
1592 <            return super.subLower(key);
1591 >        final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1592 >            SubMapEntryIterator(TreeMap.Entry<K,V> first,
1593 >                                TreeMap.Entry<K,V> fence) {
1594 >                super(first, fence);
1595 >            }
1596 >            public Map.Entry<K,V> next() {
1597 >                return nextEntry();
1598 >            }
1599          }
1600  
1601 <        @Override TreeMap.Entry<K,V> subFloor(K key) {
1602 <            return super.subCeiling(key);
1601 >        final class SubMapKeyIterator extends SubMapIterator<K> {
1602 >            SubMapKeyIterator(TreeMap.Entry<K,V> first,
1603 >                              TreeMap.Entry<K,V> fence) {
1604 >                super(first, fence);
1605 >            }
1606 >            public K next() {
1607 >                return nextEntry().key;
1608 >            }
1609          }
1610  
1611 <        @Override TreeMap.Entry<K,V> subLower(K key) {
1612 <            return super.subHigher(key);
1611 >        final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1612 >            DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
1613 >                                          TreeMap.Entry<K,V> fence) {
1614 >                super(last, fence);
1615 >            }
1616 >
1617 >            public Map.Entry<K,V> next() {
1618 >                return prevEntry();
1619 >            }
1620          }
1639    }
1621  
1622 <    /**
1623 <     * This class exists solely for the sake of serialization
1624 <     * compatibility with previous releases of TreeMap that did not
1625 <     * support NavigableMap.  It translates an old-version SubMap into
1626 <     * a new-version AscendingSubMap. This class is never otherwise
1627 <     * used.
1628 <     */
1629 <    private class SubMap extends AbstractMap<K,V>
1649 <        implements SortedMap<K,V>, java.io.Serializable {
1650 <        private static final long serialVersionUID = -6520786458950516097L;
1651 <        private boolean fromStart = false, toEnd = false;
1652 <        private K fromKey, toKey;
1653 <        private Object readResolve() {
1654 <            return new AscendingSubMap
1655 <                (fromStart? ((K)UNBOUNDED) : fromKey, 0,
1656 <                 toEnd? ((K)UNBOUNDED) : toKey, 1);
1622 >        final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
1623 >            DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
1624 >                                        TreeMap.Entry<K,V> fence) {
1625 >                super(last, fence);
1626 >            }
1627 >            public K next() {
1628 >                return prevEntry().key;
1629 >            }
1630          }
1658        public Set<Map.Entry<K,V>> entrySet() { throw new UnsupportedOperationException(); }
1659        public K lastKey() { throw new UnsupportedOperationException(); }
1660        public K firstKey() { throw new UnsupportedOperationException(); }
1661        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new UnsupportedOperationException(); }
1662        public SortedMap<K,V> headMap(K toKey) { throw new UnsupportedOperationException(); }
1663        public SortedMap<K,V> tailMap(K fromKey) { throw new UnsupportedOperationException(); }
1664        public Comparator<? super K> comparator() { throw new UnsupportedOperationException(); }
1631      }
1632  
1633 <    /**
1634 <     * TreeMap Iterator.
1669 <     */
1670 <    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1671 <        int expectedModCount = TreeMap.this.modCount;
1672 <        Entry<K,V> lastReturned = null;
1673 <        Entry<K,V> next;
1633 >    static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1634 >        private static final long serialVersionUID = 912986545866124060L;
1635  
1636 <        PrivateEntryIterator(Entry<K,V> first) {
1637 <            next = first;
1636 >        AscendingSubMap(TreeMap<K,V> m,
1637 >                        boolean fromStart, K lo, boolean loInclusive,
1638 >                        boolean toEnd, K hi, boolean hiInclusive) {
1639 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1640          }
1641  
1642 <        public final boolean hasNext() {
1643 <            return next != null;
1642 >        public Comparator<? super K> comparator() {
1643 >            return m.comparator();
1644          }
1645  
1646 <        final Entry<K,V> nextEntry() {
1647 <            if (next == null)
1648 <                throw new NoSuchElementException();
1649 <            if (modCount != expectedModCount)
1650 <                throw new ConcurrentModificationException();
1651 <            lastReturned = next;
1652 <            next = successor(next);
1653 <            return lastReturned;
1646 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1647 >                                        K toKey, boolean toInclusive) {
1648 >            if (!inRange(fromKey, fromInclusive))
1649 >                throw new IllegalArgumentException("fromKey out of range");
1650 >            if (!inRange(toKey, toInclusive))
1651 >                throw new IllegalArgumentException("toKey out of range");
1652 >            return new AscendingSubMap(m,
1653 >                                       false, fromKey, fromInclusive,
1654 >                                       false, toKey,   toInclusive);
1655          }
1656  
1657 <        final Entry<K,V> prevEntry() {
1658 <            if (next == null)
1659 <                throw new NoSuchElementException();
1660 <            if (modCount != expectedModCount)
1661 <                throw new ConcurrentModificationException();
1662 <            lastReturned = next;
1699 <            next = predecessor(next);
1700 <            return lastReturned;
1657 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1658 >            if (!inClosedRange(toKey))
1659 >                throw new IllegalArgumentException("toKey out of range");
1660 >            return new AscendingSubMap(m,
1661 >                                       fromStart, lo,    loInclusive,
1662 >                                       false,     toKey, inclusive);
1663          }
1664  
1665 <        public void remove() {
1666 <            if (lastReturned == null)
1667 <                throw new IllegalStateException();
1668 <            if (modCount != expectedModCount)
1669 <                throw new ConcurrentModificationException();
1670 <            if (lastReturned.left != null && lastReturned.right != null)
1709 <                next = lastReturned;
1710 <            deleteEntry(lastReturned);
1711 <            expectedModCount++;
1712 <            lastReturned = null;
1665 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1666 >            if (!inRange(fromKey, inclusive))
1667 >                throw new IllegalArgumentException("fromKey out of range");
1668 >            return new AscendingSubMap(m,
1669 >                                       false, fromKey, inclusive,
1670 >                                       toEnd, hi,      hiInclusive);
1671          }
1714    }
1672  
1673 <    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1674 <        EntryIterator(Entry<K,V> first) {
1675 <            super(first);
1676 <        }
1677 <        public Map.Entry<K,V> next() {
1678 <            return nextEntry();
1673 >        public NavigableMap<K,V> descendingMap() {
1674 >            NavigableMap<K,V> mv = descendingMapView;
1675 >            return (mv != null) ? mv :
1676 >                (descendingMapView =
1677 >                 new DescendingSubMap(m,
1678 >                                      fromStart, lo, loInclusive,
1679 >                                      toEnd,     hi, hiInclusive));
1680          }
1723    }
1681  
1682 <    final class ValueIterator extends PrivateEntryIterator<V> {
1683 <        ValueIterator(Entry<K,V> first) {
1727 <            super(first);
1682 >        Iterator<K> keyIterator() {
1683 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1684          }
1685 <        public V next() {
1686 <            return nextEntry().value;
1685 >
1686 >        Iterator<K> descendingKeyIterator() {
1687 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1688          }
1732    }
1689  
1690 <    final class KeyIterator extends PrivateEntryIterator<K> {
1691 <        KeyIterator(Entry<K,V> first) {
1692 <            super(first);
1690 >        final class AscendingEntrySetView extends EntrySetView {
1691 >            public Iterator<Map.Entry<K,V>> iterator() {
1692 >                return new SubMapEntryIterator(absLowest(), absHighFence());
1693 >            }
1694          }
1695 <        public K next() {
1696 <            return nextEntry().key;
1695 >
1696 >        public Set<Map.Entry<K,V>> entrySet() {
1697 >            EntrySetView es = entrySetView;
1698 >            return (es != null) ? es : new AscendingEntrySetView();
1699          }
1700 +
1701 +        TreeMap.Entry<K,V> subLowest()       { return absLowest(); }
1702 +        TreeMap.Entry<K,V> subHighest()      { return absHighest(); }
1703 +        TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); }
1704 +        TreeMap.Entry<K,V> subHigher(K key)  { return absHigher(key); }
1705 +        TreeMap.Entry<K,V> subFloor(K key)   { return absFloor(key); }
1706 +        TreeMap.Entry<K,V> subLower(K key)   { return absLower(key); }
1707      }
1708  
1709 <    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1710 <        DescendingKeyIterator(Entry<K,V> first) {
1711 <            super(first);
1712 <        }
1713 <        public K next() {
1714 <            return prevEntry().key;
1709 >    static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
1710 >        private static final long serialVersionUID = 912986545866120460L;
1711 >        DescendingSubMap(TreeMap<K,V> m,
1712 >                        boolean fromStart, K lo, boolean loInclusive,
1713 >                        boolean toEnd, K hi, boolean hiInclusive) {
1714 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1715          }
1750    }
1716  
1717 <    /**
1718 <     * Iterators for SubMaps
1754 <     */
1755 <    abstract class SubMapIterator<T> implements Iterator<T> {
1756 <        int expectedModCount = TreeMap.this.modCount;
1757 <        Entry<K,V> lastReturned = null;
1758 <        Entry<K,V> next;
1759 <        final K firstExcludedKey;
1717 >        private final Comparator<? super K> reverseComparator =
1718 >            Collections.reverseOrder(m.comparator);
1719  
1720 <        SubMapIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1721 <            next = first;
1763 <            firstExcludedKey = (firstExcluded == null ? null
1764 <                                : firstExcluded.key);
1720 >        public Comparator<? super K> comparator() {
1721 >            return reverseComparator;
1722          }
1723  
1724 <        public final boolean hasNext() {
1725 <            return next != null && next.key != firstExcludedKey;
1724 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1725 >                                        K toKey, boolean toInclusive) {
1726 >            if (!inRange(fromKey, fromInclusive))
1727 >                throw new IllegalArgumentException("fromKey out of range");
1728 >            if (!inRange(toKey, toInclusive))
1729 >                throw new IllegalArgumentException("toKey out of range");
1730 >            return new DescendingSubMap(m,
1731 >                                        false, toKey,   toInclusive,
1732 >                                        false, fromKey, fromInclusive);
1733          }
1734  
1735 <        final Entry<K,V> nextEntry() {
1736 <            if (next == null || next.key == firstExcludedKey)
1737 <                throw new NoSuchElementException();
1738 <            if (modCount != expectedModCount)
1739 <                throw new ConcurrentModificationException();
1740 <            lastReturned = next;
1777 <            next = successor(next);
1778 <            return lastReturned;
1735 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1736 >            if (!inRange(toKey, inclusive))
1737 >                throw new IllegalArgumentException("toKey out of range");
1738 >            return new DescendingSubMap(m,
1739 >                                        false, toKey, inclusive,
1740 >                                        toEnd, hi,    hiInclusive);
1741          }
1742  
1743 <        final Entry<K,V> prevEntry() {
1744 <            if (next == null || next.key == firstExcludedKey)
1745 <                throw new NoSuchElementException();
1746 <            if (modCount != expectedModCount)
1747 <                throw new ConcurrentModificationException();
1748 <            lastReturned = next;
1787 <            next = predecessor(next);
1788 <            return lastReturned;
1743 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1744 >            if (!inRange(fromKey, inclusive))
1745 >                throw new IllegalArgumentException("fromKey out of range");
1746 >            return new DescendingSubMap(m,
1747 >                                        fromStart, lo, loInclusive,
1748 >                                        false, fromKey, inclusive);
1749          }
1750  
1751 <        public void remove() {
1752 <            if (lastReturned == null)
1753 <                throw new IllegalStateException();
1754 <            if (modCount != expectedModCount)
1755 <                throw new ConcurrentModificationException();
1756 <            if (lastReturned.left != null && lastReturned.right != null)
1757 <                next = lastReturned;
1798 <            deleteEntry(lastReturned);
1799 <            expectedModCount++;
1800 <            lastReturned = null;
1751 >        public NavigableMap<K,V> descendingMap() {
1752 >            NavigableMap<K,V> mv = descendingMapView;
1753 >            return (mv != null) ? mv :
1754 >                (descendingMapView =
1755 >                 new AscendingSubMap(m,
1756 >                                     fromStart, lo, loInclusive,
1757 >                                     toEnd,     hi, hiInclusive));
1758          }
1802    }
1759  
1760 <    final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1761 <        SubMapEntryIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1806 <            super(first, firstExcluded);
1807 <        }
1808 <        public Map.Entry<K,V> next() {
1809 <            return nextEntry();
1760 >        Iterator<K> keyIterator() {
1761 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1762          }
1811    }
1763  
1764 <    final class SubMapKeyIterator extends SubMapIterator<K> {
1765 <        SubMapKeyIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1815 <            super(first, firstExcluded);
1816 <        }
1817 <        public K next() {
1818 <            return nextEntry().key;
1764 >        Iterator<K> descendingKeyIterator() {
1765 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1766          }
1820    }
1767  
1768 <    final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1769 <        DescendingSubMapEntryIterator(Entry<K,V> last, Entry<K,V> lastExcluded) {
1770 <            super(last, lastExcluded);
1768 >        final class DescendingEntrySetView extends EntrySetView {
1769 >            public Iterator<Map.Entry<K,V>> iterator() {
1770 >                return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
1771 >            }
1772          }
1773  
1774 <        public Map.Entry<K,V> next() {
1775 <            return prevEntry();
1774 >        public Set<Map.Entry<K,V>> entrySet() {
1775 >            EntrySetView es = entrySetView;
1776 >            return (es != null) ? es : new DescendingEntrySetView();
1777          }
1830    }
1778  
1779 <    final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
1780 <        DescendingSubMapKeyIterator(Entry<K,V> last, Entry<K,V> lastExcluded) {
1781 <            super(last, lastExcluded);
1782 <        }
1783 <        public K next() {
1784 <            return prevEntry().key;
1838 <        }
1779 >        TreeMap.Entry<K,V> subLowest()       { return absHighest(); }
1780 >        TreeMap.Entry<K,V> subHighest()      { return absLowest(); }
1781 >        TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
1782 >        TreeMap.Entry<K,V> subHigher(K key)  { return absLower(key); }
1783 >        TreeMap.Entry<K,V> subFloor(K key)   { return absCeiling(key); }
1784 >        TreeMap.Entry<K,V> subLower(K key)   { return absHigher(key); }
1785      }
1786  
1787      /**
1788 <     * Compares two keys using the correct comparison method for this TreeMap.
1788 >     * This class exists solely for the sake of serialization
1789 >     * compatibility with previous releases of TreeMap that did not
1790 >     * support NavigableMap.  It translates an old-version SubMap into
1791 >     * a new-version AscendingSubMap. This class is never otherwise
1792 >     * used.
1793       */
1794 <    private int compare(Object k1, Object k2) {
1795 <        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1796 <                                : comparator.compare((K)k1, (K)k2);
1794 >    private class SubMap extends AbstractMap<K,V>
1795 >        implements SortedMap<K,V>, java.io.Serializable {
1796 >        private static final long serialVersionUID = -6520786458950516097L;
1797 >        private boolean fromStart = false, toEnd = false;
1798 >        private K fromKey, toKey;
1799 >        private Object readResolve() {
1800 >            return new AscendingSubMap(TreeMap.this,
1801 >                                       fromStart, fromKey, true,
1802 >                                       toEnd, toKey, false);
1803 >        }
1804 >        public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
1805 >        public K lastKey() { throw new InternalError(); }
1806 >        public K firstKey() { throw new InternalError(); }
1807 >        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
1808 >        public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
1809 >        public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
1810 >        public Comparator<? super K> comparator() { throw new InternalError(); }
1811      }
1812  
1813 <    /**
1814 <     * Test two values for equality.  Differs from o1.equals(o2) only in
1851 <     * that it copes with <tt>null</tt> o1 properly.
1852 <     */
1853 <    private static boolean valEquals(Object o1, Object o2) {
1854 <        return (o1==null ? o2==null : o1.equals(o2));
1855 <    }
1813 >
1814 >    // Red-black mechanics
1815  
1816      private static final boolean RED   = false;
1817      private static final boolean BLACK = true;
# Line 1862 | Line 1821 | public class TreeMap<K,V>
1821       * user (see Map.Entry).
1822       */
1823  
1824 <    static class Entry<K,V> implements Map.Entry<K,V> {
1824 >    static final class Entry<K,V> implements Map.Entry<K,V> {
1825          K key;
1826          V value;
1827          Entry<K,V> left = null;
# Line 1934 | Line 1893 | public class TreeMap<K,V>
1893       * Returns the first Entry in the TreeMap (according to the TreeMap's
1894       * key-sort function).  Returns null if the TreeMap is empty.
1895       */
1896 <    private Entry<K,V> getFirstEntry() {
1896 >    final Entry<K,V> getFirstEntry() {
1897          Entry<K,V> p = root;
1898          if (p != null)
1899              while (p.left != null)
# Line 1946 | Line 1905 | public class TreeMap<K,V>
1905       * Returns the last Entry in the TreeMap (according to the TreeMap's
1906       * key-sort function).  Returns null if the TreeMap is empty.
1907       */
1908 <    private Entry<K,V> getLastEntry() {
1908 >    final Entry<K,V> getLastEntry() {
1909          Entry<K,V> p = root;
1910          if (p != null)
1911              while (p.right != null)
# Line 1957 | Line 1916 | public class TreeMap<K,V>
1916      /**
1917       * Returns the successor of the specified Entry, or null if no such.
1918       */
1919 <    private Entry<K,V> successor(Entry<K,V> t) {
1919 >    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
1920          if (t == null)
1921              return null;
1922          else if (t.right != null) {
# Line 1979 | Line 1938 | public class TreeMap<K,V>
1938      /**
1939       * Returns the predecessor of the specified Entry, or null if no such.
1940       */
1941 <    private Entry<K,V> predecessor(Entry<K,V> t) {
1941 >    static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {
1942          if (t == null)
1943              return null;
1944          else if (t.left != null) {
# Line 2029 | Line 1988 | public class TreeMap<K,V>
1988          return (p == null) ? null: p.right;
1989      }
1990  
1991 <    /** From CLR **/
1991 >    /** From CLR */
1992      private void rotateLeft(Entry<K,V> p) {
1993 <        Entry<K,V> r = p.right;
1994 <        p.right = r.left;
1995 <        if (r.left != null)
1996 <            r.left.parent = p;
1997 <        r.parent = p.parent;
1998 <        if (p.parent == null)
1999 <            root = r;
2000 <        else if (p.parent.left == p)
2001 <            p.parent.left = r;
2002 <        else
2003 <            p.parent.right = r;
2004 <        r.left = p;
2005 <        p.parent = r;
1993 >        if (p != null) {
1994 >            Entry<K,V> r = p.right;
1995 >            p.right = r.left;
1996 >            if (r.left != null)
1997 >                r.left.parent = p;
1998 >            r.parent = p.parent;
1999 >            if (p.parent == null)
2000 >                root = r;
2001 >            else if (p.parent.left == p)
2002 >                p.parent.left = r;
2003 >            else
2004 >                p.parent.right = r;
2005 >            r.left = p;
2006 >            p.parent = r;
2007 >        }
2008      }
2009  
2010 <    /** From CLR **/
2010 >    /** From CLR */
2011      private void rotateRight(Entry<K,V> p) {
2012 <        Entry<K,V> l = p.left;
2013 <        p.left = l.right;
2014 <        if (l.right != null) l.right.parent = p;
2015 <        l.parent = p.parent;
2016 <        if (p.parent == null)
2017 <            root = l;
2018 <        else if (p.parent.right == p)
2019 <            p.parent.right = l;
2020 <        else p.parent.left = l;
2021 <        l.right = p;
2022 <        p.parent = l;
2012 >        if (p != null) {
2013 >            Entry<K,V> l = p.left;
2014 >            p.left = l.right;
2015 >            if (l.right != null) l.right.parent = p;
2016 >            l.parent = p.parent;
2017 >            if (p.parent == null)
2018 >                root = l;
2019 >            else if (p.parent.right == p)
2020 >                p.parent.right = l;
2021 >            else p.parent.left = l;
2022 >            l.right = p;
2023 >            p.parent = l;
2024 >        }
2025      }
2026  
2027 <
2065 <    /** From CLR **/
2027 >    /** From CLR */
2028      private void fixAfterInsertion(Entry<K,V> x) {
2029          x.color = RED;
2030  
# Line 2081 | Line 2043 | public class TreeMap<K,V>
2043                      }
2044                      setColor(parentOf(x), BLACK);
2045                      setColor(parentOf(parentOf(x)), RED);
2046 <                    if (parentOf(parentOf(x)) != null)
2085 <                        rotateRight(parentOf(parentOf(x)));
2046 >                    rotateRight(parentOf(parentOf(x)));
2047                  }
2048              } else {
2049                  Entry<K,V> y = leftOf(parentOf(parentOf(x)));
# Line 2096 | Line 2057 | public class TreeMap<K,V>
2057                          x = parentOf(x);
2058                          rotateRight(x);
2059                      }
2060 <                    setColor(parentOf(x),  BLACK);
2060 >                    setColor(parentOf(x), BLACK);
2061                      setColor(parentOf(parentOf(x)), RED);
2062 <                    if (parentOf(parentOf(x)) != null)
2102 <                        rotateLeft(parentOf(parentOf(x)));
2062 >                    rotateLeft(parentOf(parentOf(x)));
2063                  }
2064              }
2065          }
# Line 2109 | Line 2069 | public class TreeMap<K,V>
2069      /**
2070       * Delete node p, and then rebalance the tree.
2071       */
2112
2072      private void deleteEntry(Entry<K,V> p) {
2073 <        decrementSize();
2073 >        modCount++;
2074 >        size--;
2075  
2076          // If strictly internal, copy successor's element to p and then make p
2077          // point to successor.
# Line 2157 | Line 2117 | public class TreeMap<K,V>
2117          }
2118      }
2119  
2120 <    /** From CLR **/
2120 >    /** From CLR */
2121      private void fixAfterDeletion(Entry<K,V> x) {
2122          while (x != root && colorOf(x) == BLACK) {
2123              if (x == leftOf(parentOf(x))) {
# Line 2172 | Line 2132 | public class TreeMap<K,V>
2132  
2133                  if (colorOf(leftOf(sib))  == BLACK &&
2134                      colorOf(rightOf(sib)) == BLACK) {
2135 <                    setColor(sib,  RED);
2135 >                    setColor(sib, RED);
2136                      x = parentOf(x);
2137                  } else {
2138                      if (colorOf(rightOf(sib)) == BLACK) {
# Line 2199 | Line 2159 | public class TreeMap<K,V>
2159  
2160                  if (colorOf(rightOf(sib)) == BLACK &&
2161                      colorOf(leftOf(sib)) == BLACK) {
2162 <                    setColor(sib,  RED);
2162 >                    setColor(sib, RED);
2163                      x = parentOf(x);
2164                  } else {
2165                      if (colorOf(leftOf(sib)) == BLACK) {
# Line 2265 | Line 2225 | public class TreeMap<K,V>
2225          buildFromSorted(size, null, s, null);
2226      }
2227  
2228 <    /** Intended to be called only from TreeSet.readObject **/
2228 >    /** Intended to be called only from TreeSet.readObject */
2229      void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2230          throws java.io.IOException, ClassNotFoundException {
2231          buildFromSorted(size, null, s, defaultVal);
2232      }
2233  
2234 <    /** Intended to be called only from TreeSet.addAll **/
2234 >    /** Intended to be called only from TreeSet.addAll */
2235      void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2236          try {
2237              buildFromSorted(set.size(), set.iterator(), null, defaultVal);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines