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.26 by jsr166, Tue Feb 7 20:54:24 2006 UTC vs.
Revision 1.29 by dl, Thu Apr 20 20:34:37 2006 UTC

# Line 226 | Line 226 | public class TreeMap<K,V>
226      public boolean containsValue(Object value) {
227          return (root==null ? false :
228                  (value==null ? valueSearchNull(root)
229 <                             : valueSearchNonNull(root, value)));
229 >                 : valueSearchNonNull(root, value)));
230      }
231  
232      private boolean valueSearchNull(Entry n) {
# Line 235 | Line 235 | public class TreeMap<K,V>
235  
236          // Check left and right subtrees for value
237          return (n.left  != null && valueSearchNull(n.left)) ||
238 <               (n.right != null && valueSearchNull(n.right));
238 >            (n.right != null && valueSearchNull(n.right));
239      }
240  
241      private boolean valueSearchNonNull(Entry n, Object value) {
# Line 245 | Line 245 | public class TreeMap<K,V>
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));
248 >            (n.right != null && valueSearchNonNull(n.right, value));
249      }
250  
251      /**
# Line 335 | Line 335 | public class TreeMap<K,V>
335       *         and this map uses natural ordering, or its comparator
336       *         does not permit null keys
337       */
338 <    private Entry<K,V> getEntry(Object key) {
338 >    final Entry<K,V> getEntry(Object key) {
339          // Offload comparator-based version for sake of performance
340          if (comparator != null)
341              return getEntryUsingComparator(key);
342 +        if (key == null)
343 +            throw new NullPointerException();
344          Comparable<? super K> k = (Comparable<? super K>) key;
345          Entry<K,V> p = root;
346          while (p != null) {
# Line 359 | Line 361 | public class TreeMap<K,V>
361       * that are less dependent on comparator performance, but is
362       * worthwhile here.)
363       */
364 <    private Entry<K,V> getEntryUsingComparator(Object key) {
364 >    final Entry<K,V> getEntryUsingComparator(Object key) {
365          K k = (K) key;
366          Comparator<? super K> cpr = comparator;
367          Entry<K,V> p = root;
# Line 381 | Line 383 | public class TreeMap<K,V>
383       * key; if no such entry exists (i.e., the greatest key in the Tree is less
384       * than the specified key), returns <tt>null</tt>.
385       */
386 <    private Entry<K,V> getCeilingEntry(K key) {
386 >    final Entry<K,V> getCeilingEntry(K key) {
387          Entry<K,V> p = root;
388          if (p==null)
389              return null;
# Line 415 | Line 417 | public class TreeMap<K,V>
417       * exists, returns the entry for the greatest key less than the specified
418       * key; if no such entry exists, returns <tt>null</tt>.
419       */
420 <    private Entry<K,V> getFloorEntry(K key) {
420 >    final Entry<K,V> getFloorEntry(K key) {
421          Entry<K,V> p = root;
422          if (p==null)
423              return null;
# Line 451 | Line 453 | public class TreeMap<K,V>
453       * key greater than the specified key; if no such entry exists
454       * returns <tt>null</tt>.
455       */
456 <    private Entry<K,V> getHigherEntry(K key) {
456 >    final Entry<K,V> getHigherEntry(K key) {
457          Entry<K,V> p = root;
458          if (p==null)
459              return null;
# Line 484 | Line 486 | public class TreeMap<K,V>
486       * no such entry exists (i.e., the least key in the Tree is greater than
487       * the specified key), returns <tt>null</tt>.
488       */
489 <    private Entry<K,V> getLowerEntry(K key) {
489 >    final Entry<K,V> getLowerEntry(K key) {
490          Entry<K,V> p = root;
491          if (p==null)
492              return null;
# Line 516 | Line 518 | public class TreeMap<K,V>
518       * Returns the key corresponding to the specified Entry.
519       * @throws NoSuchElementException if the Entry is null
520       */
521 <    private static <K> K key(Entry<K,?> e) {
521 >    static <K> K key(Entry<K,?> e) {
522          if (e==null)
523              throw new NoSuchElementException();
524          return e.key;
# Line 545 | Line 547 | public class TreeMap<K,V>
547  
548          if (t == null) {
549              // TBD
550 < //             if (key == null) {
551 < //                 if (comparator == null)
552 < //                     throw new NullPointerException();
553 < //                 comparator.compare(key, key);
554 < //             }
550 >            //             if (key == null) {
551 >            //                 if (comparator == null)
552 >            //                     throw new NullPointerException();
553 >            //                 comparator.compare(key, key);
554 >            //             }
555              incrementSize();
556              root = new Entry<K,V>(key, value, null);
557              return null;
# Line 634 | Line 636 | public class TreeMap<K,V>
636          clone.size = 0;
637          clone.modCount = 0;
638          clone.entrySet = null;
639 <        clone.descendingEntrySet = null;
640 <        clone.descendingKeySet = null;
639 >        clone.navigableKeySet = null;
640 >        clone.descendingMap = null;
641  
642          // Initialize clone with our mappings
643          try {
# Line 792 | Line 794 | public class TreeMap<K,V>
794       * the first time this view is requested.  Views are stateless, so
795       * there's no reason to create more than one.
796       */
797 <    private transient Set<Map.Entry<K,V>> entrySet = null;
798 <    private transient Set<Map.Entry<K,V>> descendingEntrySet = null;
799 <    private transient Set<K> descendingKeySet = null;
797 >    private transient EntrySet entrySet = null;
798 >    private transient KeySet<K> navigableKeySet = null;
799 >    private transient NavigableMap<K,V> descendingMap = null;
800  
801      /**
802       * Returns a {@link Set} view of the keys contained in this map.
# Line 811 | Line 813 | public class TreeMap<K,V>
813       * operations.
814       */
815      public Set<K> keySet() {
816 <        Set<K> ks = keySet;
815 <        return (ks != null) ? ks : (keySet = new KeySet());
816 >        return navigableKeySet();
817      }
818  
819 <    class KeySet extends AbstractSet<K> {
820 <        public Iterator<K> iterator() {
821 <            return new KeyIterator(getFirstEntry());
822 <        }
823 <
824 <        public int size() {
825 <            return TreeMap.this.size();
825 <        }
826 <
827 <        public boolean contains(Object o) {
828 <            return containsKey(o);
829 <        }
830 <
831 <        public boolean remove(Object o) {
832 <            int oldSize = size;
833 <            TreeMap.this.remove(o);
834 <            return size != oldSize;
835 <        }
819 >    /**
820 >     * @since 1.6
821 >     */
822 >    public NavigableSet<K> navigableKeySet() {
823 >        KeySet<K> nks = navigableKeySet;
824 >        return (nks != null) ? nks : (navigableKeySet = new KeySet(this));
825 >    }
826  
827 <        public void clear() {
828 <            TreeMap.this.clear();
829 <        }
827 >    /**
828 >     * @since 1.6
829 >     */
830 >    public NavigableSet<K> descendingKeySet() {
831 >        return descendingMap().navigableKeySet();
832      }
833  
834      /**
# Line 859 | Line 851 | public class TreeMap<K,V>
851          return (vs != null) ? vs : (values = new Values());
852      }
853  
854 +    /**
855 +     * Returns a {@link Set} view of the mappings contained in this map.
856 +     * The set's iterator returns the entries in ascending key order.
857 +     * The set is backed by the map, so changes to the map are
858 +     * reflected in the set, and vice-versa.  If the map is modified
859 +     * while an iteration over the set is in progress (except through
860 +     * the iterator's own <tt>remove</tt> operation, or through the
861 +     * <tt>setValue</tt> operation on a map entry returned by the
862 +     * iterator) the results of the iteration are undefined.  The set
863 +     * supports element removal, which removes the corresponding
864 +     * mapping from the map, via the <tt>Iterator.remove</tt>,
865 +     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
866 +     * <tt>clear</tt> operations.  It does not support the
867 +     * <tt>add</tt> or <tt>addAll</tt> operations.
868 +     */
869 +    public Set<Map.Entry<K,V>> entrySet() {
870 +        EntrySet es = entrySet;
871 +        return (es != null) ? es : (entrySet = new EntrySet());
872 +    }
873 +
874 +    /**
875 +     * @since 1.6
876 +     */
877 +    public NavigableMap<K, V> descendingMap() {
878 +        NavigableMap<K, V> km = descendingMap;
879 +        return (km != null) ? km :
880 +            (descendingMap = new DescendingSubMap(this,
881 +                                                  true, null, 0,
882 +                                                  true, null, 0));
883 +    }
884 +
885 +    /**
886 +     * @throws ClassCastException       {@inheritDoc}
887 +     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
888 +     *         null and this map uses natural ordering, or its comparator
889 +     *         does not permit null keys
890 +     * @throws IllegalArgumentException {@inheritDoc}
891 +     * @since 1.6
892 +     */
893 +    public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
894 +                                    K toKey,   boolean toInclusive) {
895 +        return new AscendingSubMap(this,
896 +                                   false, fromKey, excluded(fromInclusive),
897 +                                   false, toKey,   excluded(toInclusive));
898 +    }
899 +
900 +    /**
901 +     * @throws ClassCastException       {@inheritDoc}
902 +     * @throws NullPointerException if <tt>toKey</tt> is null
903 +     *         and this map uses natural ordering, or its comparator
904 +     *         does not permit null keys
905 +     * @throws IllegalArgumentException {@inheritDoc}
906 +     * @since 1.6
907 +     */
908 +    public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
909 +        return new AscendingSubMap(this,
910 +                                   true, null, 0,
911 +                                   false, toKey, excluded(inclusive));
912 +    }
913 +
914 +    /**
915 +     * @throws ClassCastException       {@inheritDoc}
916 +     * @throws NullPointerException if <tt>fromKey</tt> is null
917 +     *         and this map uses natural ordering, or its comparator
918 +     *         does not permit null keys
919 +     * @throws IllegalArgumentException {@inheritDoc}
920 +     * @since 1.6
921 +     */
922 +    public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
923 +        return new AscendingSubMap(this,
924 +                                   false, fromKey, excluded(inclusive),
925 +                                   true, null, 0);
926 +    }
927 +
928 +    /**
929 +     * Translates a boolean "inclusive" value to the correct int value
930 +     * for the loExcluded or hiExcluded field.
931 +     */
932 +    static int excluded(boolean inclusive) {
933 +        return inclusive ? 0 : 1;
934 +    }
935 +
936 +    /**
937 +     * @throws ClassCastException       {@inheritDoc}
938 +     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
939 +     *         null and this map uses natural ordering, or its comparator
940 +     *         does not permit null keys
941 +     * @throws IllegalArgumentException {@inheritDoc}
942 +     */
943 +    public SortedMap<K,V> subMap(K fromKey, K toKey) {
944 +        return subMap(fromKey, true, toKey, false);
945 +    }
946 +
947 +    /**
948 +     * @throws ClassCastException       {@inheritDoc}
949 +     * @throws NullPointerException if <tt>toKey</tt> is null
950 +     *         and this map uses natural ordering, or its comparator
951 +     *         does not permit null keys
952 +     * @throws IllegalArgumentException {@inheritDoc}
953 +     */
954 +    public SortedMap<K,V> headMap(K toKey) {
955 +        return headMap(toKey, false);
956 +    }
957 +
958 +    /**
959 +     * @throws ClassCastException       {@inheritDoc}
960 +     * @throws NullPointerException if <tt>fromKey</tt> is null
961 +     *         and this map uses natural ordering, or its comparator
962 +     *         does not permit null keys
963 +     * @throws IllegalArgumentException {@inheritDoc}
964 +     */
965 +    public SortedMap<K,V> tailMap(K fromKey) {
966 +        return tailMap(fromKey, true);
967 +    }
968 +
969 +    // View class support
970 +
971      class Values extends AbstractCollection<V> {
972          public Iterator<V> iterator() {
973              return new ValueIterator(getFirstEntry());
# Line 890 | Line 999 | public class TreeMap<K,V>
999          }
1000      }
1001  
893    /**
894     * Returns a {@link Set} view of the mappings contained in this map.
895     * The set's iterator returns the entries in ascending key order.
896     * The set is backed by the map, so changes to the map are
897     * reflected in the set, and vice-versa.  If the map is modified
898     * while an iteration over the set is in progress (except through
899     * the iterator's own <tt>remove</tt> operation, or through the
900     * <tt>setValue</tt> operation on a map entry returned by the
901     * iterator) the results of the iteration are undefined.  The set
902     * supports element removal, which removes the corresponding
903     * mapping from the map, via the <tt>Iterator.remove</tt>,
904     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
905     * <tt>clear</tt> operations.  It does not support the
906     * <tt>add</tt> or <tt>addAll</tt> operations.
907     */
908    public Set<Map.Entry<K,V>> entrySet() {
909        Set<Map.Entry<K,V>> es = entrySet;
910        return (es != null) ? es : (entrySet = new EntrySet());
911    }
912
1002      class EntrySet extends AbstractSet<Map.Entry<K,V>> {
1003          public Iterator<Map.Entry<K,V>> iterator() {
1004              return new EntryIterator(getFirstEntry());
# Line 946 | Line 1035 | public class TreeMap<K,V>
1035          }
1036      }
1037  
1038 <    /**
1039 <     * @since 1.6
1038 >    /*
1039 >     * Unlike Values and EntrySet, the KeySet class is static,
1040 >     * delegating to a NavigableMap to allow use by SubMaps, which
1041 >     * outweighs the ugliness of needing type-tests for the following
1042 >     * Iterator methods that are defined appropriately in main versus
1043 >     * submap classes.
1044       */
952    public Set<Map.Entry<K,V>> descendingEntrySet() {
953        Set<Map.Entry<K,V>> es = descendingEntrySet;
954        return (es != null) ? es : (descendingEntrySet = new DescendingEntrySet());
955    }
1045  
1046 <    class DescendingEntrySet extends EntrySet {
1047 <        public Iterator<Map.Entry<K,V>> iterator() {
959 <            return new DescendingEntryIterator(getLastEntry());
960 <        }
1046 >    Iterator<K> keyIterator() {
1047 >        return new KeyIterator(getFirstEntry());
1048      }
1049  
1050 <    /**
1051 <     * @since 1.6
965 <     */
966 <    public Set<K> descendingKeySet() {
967 <        Set<K> ks = descendingKeySet;
968 <        return (ks != null) ? ks : (descendingKeySet = new DescendingKeySet());
1050 >    Iterator<K> descendingKeyIterator() {
1051 >        return new DescendingKeyIterator(getFirstEntry());
1052      }
1053  
1054 <    class DescendingKeySet extends KeySet {
1055 <        public Iterator<K> iterator() {
1056 <            return new DescendingKeyIterator(getLastEntry());
1054 >    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
1055 >        private final NavigableMap<E, Object> m;
1056 >        KeySet(NavigableMap<E,Object> map) { m = map; }
1057 >
1058 >        public Iterator<E> iterator() {
1059 >            if (m instanceof TreeMap)
1060 >                return ((TreeMap<E,Object>)m).keyIterator();
1061 >            else
1062 >                return (Iterator<E>)(((TreeMap.NavigableSubMap)m).keyIterator());
1063          }
975    }
1064  
1065 <    /**
1066 <     * @throws ClassCastException       {@inheritDoc}
1067 <     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
1068 <     *         null and this map uses natural ordering, or its comparator
1069 <     *         does not permit null keys
1070 <     * @throws IllegalArgumentException {@inheritDoc}
1071 <     * @since 1.6
1072 <     */
1073 <    public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1074 <        return new SubMap(fromKey, toKey);
1065 >        public Iterator<E> descendingIterator() {
1066 >            if (m instanceof TreeMap)
1067 >                return ((TreeMap<E,Object>)m).descendingKeyIterator();
1068 >            else
1069 >                return (Iterator<E>)(((TreeMap.NavigableSubMap)m).descendingKeyIterator());
1070 >        }
1071 >
1072 >        public int size() { return m.size(); }
1073 >        public boolean isEmpty() { return m.isEmpty(); }
1074 >        public boolean contains(Object o) { return m.containsKey(o); }
1075 >        public void clear() { m.clear(); }
1076 >        public E lower(E e) { return m.lowerKey(e); }
1077 >        public E floor(E e) { return m.floorKey(e); }
1078 >        public E ceiling(E e) { return m.ceilingKey(e); }
1079 >        public E higher(E e) { return m.higherKey(e); }
1080 >        public E first() { return m.firstKey(); }
1081 >        public E last() { return m.lastKey(); }
1082 >        public Comparator<? super E> comparator() { return m.comparator(); }
1083 >        public E pollFirst() {
1084 >            Map.Entry<E,Object> e = m.pollFirstEntry();
1085 >            return e == null? null : e.getKey();
1086 >        }
1087 >        public E pollLast() {
1088 >            Map.Entry<E,Object> e = m.pollLastEntry();
1089 >            return e == null? null : e.getKey();
1090 >        }
1091 >        public boolean remove(Object o) {
1092 >            int oldSize = size();
1093 >            m.remove(o);
1094 >            return size() != oldSize;
1095 >        }
1096 >        public NavigableSet<E> subSet(E fromElement,
1097 >                                      boolean fromInclusive,
1098 >                                      E toElement,
1099 >                                      boolean toInclusive) {
1100 >            return new TreeSet<E>
1101 >                (m.subMap(fromElement, fromInclusive,
1102 >                          toElement,   toInclusive));
1103 >        }
1104 >        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1105 >            return new TreeSet<E>(m.headMap(toElement, inclusive));
1106 >        }
1107 >        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1108 >            return new TreeSet<E>(m.tailMap(fromElement, inclusive));
1109 >        }
1110 >        public SortedSet<E> subSet(E fromElement, E toElement) {
1111 >            return subSet(fromElement, true, toElement, false);
1112 >        }
1113 >        public SortedSet<E> headSet(E toElement) {
1114 >            return headSet(toElement, false);
1115 >        }
1116 >        public SortedSet<E> tailSet(E fromElement) {
1117 >            return tailSet(fromElement, true);
1118 >        }
1119 >        public NavigableSet<E> descendingSet() {
1120 >            return new TreeSet(m.descendingMap());
1121 >        }
1122      }
1123  
1124      /**
1125 <     * @throws ClassCastException       {@inheritDoc}
991 <     * @throws NullPointerException if <tt>toKey</tt> is null
992 <     *         and this map uses natural ordering, or its comparator
993 <     *         does not permit null keys
994 <     * @throws IllegalArgumentException {@inheritDoc}
995 <     * @since 1.6
1125 >     * Base class for TreeMap Iterators
1126       */
1127 <    public NavigableMap<K,V> navigableHeadMap(K toKey) {
1128 <        return new SubMap(toKey, true);
1127 >    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1128 >        int expectedModCount = TreeMap.this.modCount;
1129 >        Entry<K,V> lastReturned = null;
1130 >        Entry<K,V> next;
1131 >
1132 >        PrivateEntryIterator(Entry<K,V> first) {
1133 >            next = first;
1134 >        }
1135 >
1136 >        public final boolean hasNext() {
1137 >            return next != null;
1138 >        }
1139 >
1140 >        final Entry<K,V> nextEntry() {
1141 >            if (next == null)
1142 >                throw new NoSuchElementException();
1143 >            if (modCount != expectedModCount)
1144 >                throw new ConcurrentModificationException();
1145 >            lastReturned = next;
1146 >            next = successor(next);
1147 >            return lastReturned;
1148 >        }
1149 >
1150 >        final Entry<K,V> prevEntry() {
1151 >            if (next == null)
1152 >                throw new NoSuchElementException();
1153 >            if (modCount != expectedModCount)
1154 >                throw new ConcurrentModificationException();
1155 >            lastReturned = next;
1156 >            next = predecessor(next);
1157 >            return lastReturned;
1158 >        }
1159 >
1160 >        public void remove() {
1161 >            if (lastReturned == null)
1162 >                throw new IllegalStateException();
1163 >            if (modCount != expectedModCount)
1164 >                throw new ConcurrentModificationException();
1165 >            if (lastReturned.left != null && lastReturned.right != null)
1166 >                next = lastReturned;
1167 >            deleteEntry(lastReturned);
1168 >            expectedModCount++;
1169 >            lastReturned = null;
1170 >        }
1171      }
1172  
1173 <    /**
1174 <     * @throws ClassCastException       {@inheritDoc}
1175 <     * @throws NullPointerException if <tt>fromKey</tt> is null
1176 <     *         and this map uses natural ordering, or its comparator
1177 <     *         does not permit null keys
1178 <     * @throws IllegalArgumentException {@inheritDoc}
1179 <     * @since 1.6
1008 <     */
1009 <    public NavigableMap<K,V> navigableTailMap(K fromKey) {
1010 <        return new SubMap(fromKey, false);
1173 >    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1174 >        EntryIterator(Entry<K,V> first) {
1175 >            super(first);
1176 >        }
1177 >        public Map.Entry<K,V> next() {
1178 >            return nextEntry();
1179 >        }
1180      }
1181  
1182 <    /**
1183 <     * Equivalent to {@link #navigableSubMap} but with a return type
1184 <     * conforming to the <tt>SortedMap</tt> interface.
1185 <     *
1186 <     * <p>{@inheritDoc}
1187 <     *
1188 <     * @throws ClassCastException       {@inheritDoc}
1020 <     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
1021 <     *         null and this map uses natural ordering, or its comparator
1022 <     *         does not permit null keys
1023 <     * @throws IllegalArgumentException {@inheritDoc}
1024 <     */
1025 <    public SortedMap<K,V> subMap(K fromKey, K toKey) {
1026 <        return new SubMap(fromKey, toKey);
1182 >    final class ValueIterator extends PrivateEntryIterator<V> {
1183 >        ValueIterator(Entry<K,V> first) {
1184 >            super(first);
1185 >        }
1186 >        public V next() {
1187 >            return nextEntry().value;
1188 >        }
1189      }
1190  
1191 <    /**
1192 <     * Equivalent to {@link #navigableHeadMap} but with a return type
1193 <     * conforming to the <tt>SortedMap</tt> interface.
1194 <     *
1195 <     * <p>{@inheritDoc}
1196 <     *
1197 <     * @throws ClassCastException       {@inheritDoc}
1036 <     * @throws NullPointerException if <tt>toKey</tt> is null
1037 <     *         and this map uses natural ordering, or its comparator
1038 <     *         does not permit null keys
1039 <     * @throws IllegalArgumentException {@inheritDoc}
1040 <     */
1041 <    public SortedMap<K,V> headMap(K toKey) {
1042 <        return new SubMap(toKey, true);
1191 >    final class KeyIterator extends PrivateEntryIterator<K> {
1192 >        KeyIterator(Entry<K,V> first) {
1193 >            super(first);
1194 >        }
1195 >        public K next() {
1196 >            return nextEntry().key;
1197 >        }
1198      }
1199  
1200 <    /**
1201 <     * Equivalent to {@link #navigableTailMap} but with a return type
1202 <     * conforming to the <tt>SortedMap</tt> interface.
1203 <     *
1204 <     * <p>{@inheritDoc}
1205 <     *
1206 <     * @throws ClassCastException       {@inheritDoc}
1052 <     * @throws NullPointerException if <tt>fromKey</tt> is null
1053 <     *         and this map uses natural ordering, or its comparator
1054 <     *         does not permit null keys
1055 <     * @throws IllegalArgumentException {@inheritDoc}
1056 <     */
1057 <    public SortedMap<K,V> tailMap(K fromKey) {
1058 <        return new SubMap(fromKey, false);
1200 >    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1201 >        DescendingKeyIterator(Entry<K,V> first) {
1202 >            super(first);
1203 >        }
1204 >        public K next() {
1205 >            return prevEntry().key;
1206 >        }
1207      }
1208  
1209 <    private class SubMap
1210 <        extends AbstractMap<K,V>
1211 <        implements NavigableMap<K,V>, java.io.Serializable {
1212 <        private static final long serialVersionUID = -6520786458950516097L;
1209 >    // SubMaps
1210 >
1211 >    static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
1212 >        implements NavigableMap<K,V>, java.io.Serializable {
1213 >
1214 >        /*
1215 >         * The backing map.
1216 >         */
1217 >        final TreeMap<K,V> m;
1218 >
1219 >        /** True if low point is from start of backing map */
1220 >        boolean fromStart;
1221 >
1222 >        /**
1223 >         * The low endpoint of this submap in absolute terms, or null
1224 >         * if fromStart.
1225 >         */
1226 >        K lo;
1227  
1228          /**
1229 <         * fromKey is significant only if fromStart is false.  Similarly,
1230 <         * toKey is significant only if toStart is false.
1229 >         * Zero if the low endpoint is excluded from this submap, one if
1230 >         * it's included.  This field is unused if fromStart.
1231           */
1232 <        private boolean fromStart = false, toEnd = false;
1071 <        private K fromKey, toKey;
1232 >        int loExcluded;
1233  
1234 <        SubMap(K fromKey, K toKey) {
1235 <            if (compare(fromKey, toKey) > 0)
1075 <                throw new IllegalArgumentException("fromKey > toKey");
1076 <            this.fromKey = fromKey;
1077 <            this.toKey = toKey;
1078 <        }
1234 >        /** True if high point is to End of backing map */
1235 >        boolean toEnd;
1236  
1237 <        SubMap(K key, boolean headMap) {
1238 <            compare(key, key); // Type-check key
1237 >        /**
1238 >         * The high endpoint of this submap in absolute terms, or null
1239 >         * if toEnd.
1240 >         */
1241 >        K hi;
1242  
1243 <            if (headMap) {
1244 <                fromStart = true;
1245 <                toKey = key;
1246 <            } else {
1247 <                toEnd = true;
1088 <                fromKey = key;
1089 <            }
1090 <        }
1243 >        /**
1244 >         * Zero if the high endpoint is excluded from this submap, one if
1245 >         * it's included.  This field is unused if toEnd.
1246 >         */
1247 >        int hiExcluded;
1248  
1249 <        SubMap(boolean fromStart, K fromKey, boolean toEnd, K toKey) {
1249 >        NavigableSubMap(TreeMap<K,V> m,
1250 >                        boolean fromStart, K lo, int loExcluded,
1251 >                        boolean toEnd, K hi, int hiExcluded) {
1252 >            if (!fromStart && !toEnd && m.compare(lo, hi) > 0)
1253 >                throw new IllegalArgumentException("fromKey > toKey");
1254 >            this.m = m;
1255              this.fromStart = fromStart;
1256 <            this.fromKey= fromKey;
1256 >            this.lo = lo;
1257 >            this.loExcluded = loExcluded;
1258              this.toEnd = toEnd;
1259 <            this.toKey = toKey;
1259 >            this.hi = hi;
1260 >            this.hiExcluded = hiExcluded;
1261          }
1262  
1263 <        public boolean isEmpty() {
1264 <            return entrySet().isEmpty();
1263 >        // internal utilities
1264 >
1265 >        final boolean inRange(Object key) {
1266 >            return (fromStart || m.compare(key, lo) >= loExcluded)
1267 >                && (toEnd || m.compare(hi, key) >= hiExcluded);
1268          }
1269  
1270 <        public boolean containsKey(Object key) {
1271 <            return inRange(key) && TreeMap.this.containsKey(key);
1270 >        final boolean inClosedRange(Object key) {
1271 >            return (fromStart || m.compare(key, lo) >= 0)
1272 >                && (toEnd || m.compare(hi, key) >= 0);
1273          }
1274  
1275 <        public V get(Object key) {
1276 <            if (!inRange(key))
1109 <                return null;
1110 <            return TreeMap.this.get(key);
1275 >        final boolean inRange(Object key, boolean inclusive) {
1276 >            return inclusive ? inRange(key) : inClosedRange(key);
1277          }
1278  
1279 <        public V put(K key, V value) {
1280 <            if (!inRange(key))
1115 <                throw new IllegalArgumentException("key out of range");
1116 <            return TreeMap.this.put(key, value);
1279 >        final boolean tooLow(K key) {
1280 >            return !fromStart && m.compare(key, lo) < loExcluded;
1281          }
1282  
1283 <        public V remove(Object key) {
1284 <            if (!inRange(key))
1121 <                return null;
1122 <            return TreeMap.this.remove(key);
1283 >        final boolean tooHigh(K key) {
1284 >            return !toEnd && m.compare(hi, key) < hiExcluded;
1285          }
1286  
1287 <        public Comparator<? super K> comparator() {
1288 <            return comparator;
1287 >
1288 >        /** Returns the lowest entry in this submap (absolute ordering) */
1289 >        final TreeMap.Entry<K,V> loEntry() {
1290 >            TreeMap.Entry<K,V> result =
1291 >                (fromStart ?  m.getFirstEntry() :
1292 >                 (loExcluded == 0 ? m.getCeilingEntry(lo) :
1293 >                                    m.getHigherEntry(lo)));
1294 >            return (result == null || tooHigh(result.key)) ? null : result;
1295          }
1296  
1297 <        public K firstKey() {
1298 <            TreeMap.Entry<K,V> e = fromStart ? getFirstEntry() : getCeilingEntry(fromKey);
1299 <            K first = key(e);
1300 <            if (!toEnd && compare(first, toKey) >= 0)
1301 <                throw new NoSuchElementException();
1302 <            return first;
1297 >        /** Returns the highest key in this submap (absolute ordering) */
1298 >        final TreeMap.Entry<K,V> hiEntry() {
1299 >            TreeMap.Entry<K,V> result =
1300 >                (toEnd ?  m.getLastEntry() :
1301 >                 (hiExcluded == 0 ?  m.getFloorEntry(hi) :
1302 >                                     m.getLowerEntry(hi)));
1303 >            return (result == null || tooLow(result.key)) ? null : result;
1304          }
1305  
1306 <        public K lastKey() {
1307 <            TreeMap.Entry<K,V> e = toEnd ? getLastEntry() : getLowerEntry(toKey);
1308 <            K last = key(e);
1309 <            if (!fromStart && compare(last, fromKey) < 0)
1310 <                throw new NoSuchElementException();
1311 <            return last;
1306 >        /** Polls the lowest entry in this submap (absolute ordering) */
1307 >        final Map.Entry<K,V> pollLoEntry() {
1308 >            TreeMap.Entry<K,V> e = loEntry();
1309 >            if (e == null)
1310 >                return null;
1311 >            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1312 >            m.deleteEntry(e);
1313 >            return result;
1314          }
1315  
1316 <        public Map.Entry<K,V> firstEntry() {
1317 <            TreeMap.Entry<K,V> e = fromStart ?
1318 <                getFirstEntry() : getCeilingEntry(fromKey);
1319 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1316 >        /** Polls the highest key in this submap (absolute ordering) */
1317 >        final Map.Entry<K,V> pollHiEntry() {
1318 >            TreeMap.Entry<K,V> e = hiEntry();
1319 >            if (e == null)
1320                  return null;
1321 <            return e;
1321 >            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1322 >            m.deleteEntry(e);
1323 >            return result;
1324          }
1325  
1326 <        public Map.Entry<K,V> lastEntry() {
1327 <            TreeMap.Entry<K,V> e = toEnd ?
1328 <                getLastEntry() : getLowerEntry(toKey);
1329 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1326 >        /**
1327 >         * Return the absolute high fence for ascending traversal
1328 >         */
1329 >        final TreeMap.Entry<K,V> hiFence() {
1330 >            if (toEnd)
1331                  return null;
1332 <            return e;
1332 >            else if (hiExcluded == 0)
1333 >                 return m.getHigherEntry(hi);
1334 >            else
1335 >                return m.getCeilingEntry(hi);
1336          }
1337  
1338 <        public Map.Entry<K,V> pollFirstEntry() {
1339 <            TreeMap.Entry<K,V> e = fromStart ?
1340 <                getFirstEntry() : getCeilingEntry(fromKey);
1341 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1338 >        /**
1339 >         * Return the absolute low fence for descending traversal
1340 >         */
1341 >        final TreeMap.Entry<K,V> loFence() {
1342 >            if (fromStart)
1343                  return null;
1344 <            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1345 <            deleteEntry(e);
1346 <            return result;
1344 >            else if (loExcluded == 0)
1345 >                return m.getLowerEntry(lo);
1346 >            else
1347 >                return m.getFloorEntry(lo);
1348          }
1349  
1350 <        public Map.Entry<K,V> pollLastEntry() {
1351 <            TreeMap.Entry<K,V> e = toEnd ?
1352 <                getLastEntry() : getLowerEntry(toKey);
1353 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1350 >
1351 >        public boolean isEmpty() {
1352 >            return entrySet().isEmpty();
1353 >        }
1354 >
1355 >        public boolean containsKey(Object key) {
1356 >            return inRange(key) && m.containsKey(key);
1357 >        }
1358 >
1359 >        public V get(Object key) {
1360 >            if (!inRange(key))
1361                  return null;
1362 <            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1177 <            deleteEntry(e);
1178 <            return result;
1362 >            return m.get(key);
1363          }
1364  
1365 <        private TreeMap.Entry<K,V> subceiling(K key) {
1366 <            TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1367 <                getCeilingEntry(fromKey) : getCeilingEntry(key);
1368 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1365 >        public V put(K key, V value) {
1366 >            if (!inRange(key))
1367 >                throw new IllegalArgumentException("key out of range");
1368 >            return m.put(key, value);
1369 >        }
1370 >
1371 >        public V remove(Object key) {
1372 >            if (!inRange(key))
1373                  return null;
1374 <            return e;
1374 >            return m.remove(key);
1375          }
1376  
1377          public Map.Entry<K,V> ceilingEntry(K key) {
1378 <            TreeMap.Entry<K,V> e = subceiling(key);
1378 >            TreeMap.Entry<K,V> e = subCeiling(key);
1379              return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1380          }
1381  
1382          public K ceilingKey(K key) {
1383 <            TreeMap.Entry<K,V> e = subceiling(key);
1383 >            TreeMap.Entry<K,V> e = subCeiling(key);
1384              return e == null? null : e.key;
1385          }
1386  
1199
1200        private TreeMap.Entry<K,V> subhigher(K key) {
1201            TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1202                getCeilingEntry(fromKey) : getHigherEntry(key);
1203            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1204                return null;
1205            return e;
1206        }
1207
1387          public Map.Entry<K,V> higherEntry(K key) {
1388 <            TreeMap.Entry<K,V> e = subhigher(key);
1388 >            TreeMap.Entry<K,V> e = subHigher(key);
1389              return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1390          }
1391  
1392          public K higherKey(K key) {
1393 <            TreeMap.Entry<K,V> e = subhigher(key);
1393 >            TreeMap.Entry<K,V> e = subHigher(key);
1394              return e == null? null : e.key;
1395          }
1396  
1218        private TreeMap.Entry<K,V> subfloor(K key) {
1219            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1220                getLowerEntry(toKey) : getFloorEntry(key);
1221            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1222                return null;
1223            return e;
1224        }
1225
1397          public Map.Entry<K,V> floorEntry(K key) {
1398 <            TreeMap.Entry<K,V> e = subfloor(key);
1398 >            TreeMap.Entry<K,V> e = subFloor(key);
1399              return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1400          }
1401  
1402          public K floorKey(K key) {
1403 <            TreeMap.Entry<K,V> e = subfloor(key);
1403 >            TreeMap.Entry<K,V> e = subFloor(key);
1404              return e == null? null : e.key;
1405          }
1406  
1236        private TreeMap.Entry<K,V> sublower(K key) {
1237            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1238                getLowerEntry(toKey) :  getLowerEntry(key);
1239            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1240                return null;
1241            return e;
1242        }
1243
1407          public Map.Entry<K,V> lowerEntry(K key) {
1408 <            TreeMap.Entry<K,V> e = sublower(key);
1408 >            TreeMap.Entry<K,V> e = subLower(key);
1409              return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1410          }
1411  
1412          public K lowerKey(K key) {
1413 <            TreeMap.Entry<K,V> e = sublower(key);
1413 >            TreeMap.Entry<K,V> e = subLower(key);
1414              return e == null? null : e.key;
1415          }
1416  
1417 <        private transient Set<Map.Entry<K,V>> entrySet = null;
1417 >        abstract Iterator<K> keyIterator();
1418 >        abstract Iterator<K> descendingKeyIterator();
1419  
1420 <        public Set<Map.Entry<K,V>> entrySet() {
1421 <            Set<Map.Entry<K,V>> es = entrySet;
1258 <            return (es != null)? es : (entrySet = new EntrySetView());
1420 >        public NavigableSet<K> descendingKeySet() {
1421 >            return descendingMap().navigableKeySet();
1422          }
1423  
1424 <        private class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1424 >        // Views
1425 >        transient NavigableMap<K,V> descendingMapView = null;
1426 >        transient EntrySetView entrySetView = null;
1427 >        transient KeySet<K> navigableKeySetView = null;
1428 >
1429 >        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1430              private transient int size = -1, sizeModCount;
1431  
1432              public int size() {
1433 <                if (size == -1 || sizeModCount != TreeMap.this.modCount) {
1434 <                    size = 0;  sizeModCount = TreeMap.this.modCount;
1433 >                if (fromStart && toEnd)
1434 >                    return m.size();
1435 >                if (size == -1 || sizeModCount != m.modCount) {
1436 >                    sizeModCount = m.modCount;
1437 >                    size = 0;  
1438                      Iterator i = iterator();
1439                      while (i.hasNext()) {
1440                          size++;
# Line 1274 | Line 1445 | public class TreeMap<K,V>
1445              }
1446  
1447              public boolean isEmpty() {
1448 <                return !iterator().hasNext();
1448 >                TreeMap.Entry<K,V> n = loEntry();
1449 >                return n == null || tooHigh(n.key);
1450              }
1451  
1452              public boolean contains(Object o) {
# Line 1284 | Line 1456 | public class TreeMap<K,V>
1456                  K key = entry.getKey();
1457                  if (!inRange(key))
1458                      return false;
1459 <                TreeMap.Entry node = getEntry(key);
1459 >                TreeMap.Entry node = m.getEntry(key);
1460                  return node != null &&
1461 <                       valEquals(node.getValue(), entry.getValue());
1461 >                    valEquals(node.getValue(), entry.getValue());
1462              }
1463  
1464              public boolean remove(Object o) {
# Line 1296 | Line 1468 | public class TreeMap<K,V>
1468                  K key = entry.getKey();
1469                  if (!inRange(key))
1470                      return false;
1471 <                TreeMap.Entry<K,V> node = getEntry(key);
1471 >                TreeMap.Entry<K,V> node = m.getEntry(key);
1472                  if (node!=null && valEquals(node.getValue(),entry.getValue())){
1473 <                    deleteEntry(node);
1473 >                    m.deleteEntry(node);
1474                      return true;
1475                  }
1476                  return false;
1477              }
1478 +        }
1479  
1480 <            public Iterator<Map.Entry<K,V>> iterator() {
1481 <                return new SubMapEntryIterator(
1482 <                    (fromStart ? getFirstEntry() : getCeilingEntry(fromKey)),
1483 <                    (toEnd     ? null            : getCeilingEntry(toKey)));
1311 <            }
1480 >        public NavigableSet<K> navigableKeySet() {
1481 >            KeySet<K> nksv = navigableKeySetView;
1482 >            return (nksv != null) ? nksv :
1483 >                (navigableKeySetView = new TreeMap.KeySet(this));
1484          }
1485  
1486 <        private transient Set<Map.Entry<K,V>> descendingEntrySetView = null;
1487 <        private transient Set<K> descendingKeySetView = null;
1486 >        public Set<K> keySet() {
1487 >            return navigableKeySet();
1488 >        }
1489  
1490 <        public Set<Map.Entry<K,V>> descendingEntrySet() {
1491 <            Set<Map.Entry<K,V>> es = descendingEntrySetView;
1319 <            return (es != null) ? es :
1320 <                (descendingEntrySetView = new DescendingEntrySetView());
1490 >        public SortedMap<K,V> subMap(K fromKey, K toKey) {
1491 >            return subMap(fromKey, true, toKey, false);
1492          }
1493  
1494 <        public Set<K> descendingKeySet() {
1495 <            Set<K> ks = descendingKeySetView;
1325 <            return (ks != null) ? ks :
1326 <                (descendingKeySetView = new DescendingKeySetView());
1494 >        public SortedMap<K,V> headMap(K toKey) {
1495 >            return headMap(toKey, false);
1496          }
1497  
1498 <        private class DescendingEntrySetView extends EntrySetView {
1499 <            public Iterator<Map.Entry<K,V>> iterator() {
1500 <                return new DescendingSubMapEntryIterator
1501 <                    ((toEnd     ? getLastEntry()  : getLowerEntry(toKey)),
1502 <                     (fromStart ? null            : getLowerEntry(fromKey)));
1498 >        public SortedMap<K,V> tailMap(K fromKey) {
1499 >            return tailMap(fromKey, true);
1500 >        }
1501 >
1502 >
1503 >        // The following four definitions are correct only for
1504 >        // ascending submaps. They are overridden in DescendingSubMap.
1505 >        // They are defined in the base class because the definitions
1506 >        // in DescendingSubMap rely on those for AscendingSubMap.
1507 >
1508 >        /**
1509 >         * Returns the entry corresponding to the ceiling of the specified
1510 >         * key from the perspective of this submap, or null if the submap
1511 >         * contains no such entry.
1512 >         */
1513 >        TreeMap.Entry<K,V> subCeiling(K key) {
1514 >            if (tooLow(key))
1515 >                return loEntry();
1516 >            TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
1517 >            return (e == null || tooHigh(e.key)) ? null : e;
1518 >        }
1519 >
1520 >        /**
1521 >         * Returns the entry corresponding to the higher of the specified
1522 >         * key from the perspective of this submap, or null if the submap
1523 >         * contains no such entry.
1524 >         */
1525 >        TreeMap.Entry<K,V> subHigher(K key) {
1526 >            if (tooLow(key))
1527 >                return loEntry();
1528 >            TreeMap.Entry<K,V> e = m.getHigherEntry(key);
1529 >            return (e == null || tooHigh(e.key)) ? null : e;
1530 >        }
1531 >
1532 >        /**
1533 >         * Returns the entry corresponding to the floor of the specified
1534 >         * key from the perspective of this submap, or null if the submap
1535 >         * contains no such entry.
1536 >         */
1537 >        TreeMap.Entry<K,V> subFloor(K key) {
1538 >            if (tooHigh(key))
1539 >                return hiEntry();
1540 >            TreeMap.Entry<K,V> e = m.getFloorEntry(key);
1541 >            return (e == null || tooLow(e.key)) ? null : e;
1542 >        }
1543 >
1544 >        /**
1545 >         * Returns the entry corresponding to the lower of the specified
1546 >         * key from the perspective of this submap, or null if the submap
1547 >         * contains no such entry.
1548 >         */
1549 >        TreeMap.Entry<K,V> subLower(K key) {
1550 >            if (tooHigh(key))
1551 >                return hiEntry();
1552 >            TreeMap.Entry<K,V> e = m.getLowerEntry(key);
1553 >            return (e == null || tooLow(e.key)) ? null : e;
1554 >        }
1555 >
1556 >        /**
1557 >         * Iterators for SubMaps
1558 >         */
1559 >        abstract class SubMapIterator<T> implements Iterator<T> {
1560 >            int expectedModCount = m.modCount;
1561 >            TreeMap.Entry<K,V> lastReturned = null;
1562 >            TreeMap.Entry<K,V> next;
1563 >            final K firstExcludedKey;
1564 >
1565 >            SubMapIterator(TreeMap.Entry<K,V> first,
1566 >                           TreeMap.Entry<K,V> firstExcluded) {
1567 >                next = first;
1568 >                firstExcludedKey = (firstExcluded == null ? null
1569 >                                    : firstExcluded.key);
1570 >            }
1571 >
1572 >            public final boolean hasNext() {
1573 >                return next != null && next.key != firstExcludedKey;
1574 >            }
1575 >
1576 >            final TreeMap.Entry<K,V> nextEntry() {
1577 >                if (next == null || next.key == firstExcludedKey)
1578 >                    throw new NoSuchElementException();
1579 >                if (m.modCount != expectedModCount)
1580 >                    throw new ConcurrentModificationException();
1581 >                lastReturned = next;
1582 >                next = m.successor(next);
1583 >                return lastReturned;
1584 >            }
1585 >
1586 >            final TreeMap.Entry<K,V> prevEntry() {
1587 >                if (next == null || next.key == firstExcludedKey)
1588 >                    throw new NoSuchElementException();
1589 >                if (m.modCount != expectedModCount)
1590 >                    throw new ConcurrentModificationException();
1591 >                lastReturned = next;
1592 >                next = m.predecessor(next);
1593 >                return lastReturned;
1594 >            }
1595 >
1596 >            public void remove() {
1597 >                if (lastReturned == null)
1598 >                    throw new IllegalStateException();
1599 >                if (m.modCount != expectedModCount)
1600 >                    throw new ConcurrentModificationException();
1601 >                if (lastReturned.left != null && lastReturned.right != null)
1602 >                    next = lastReturned;
1603 >                m.deleteEntry(lastReturned);
1604 >                expectedModCount++;
1605 >                lastReturned = null;
1606              }
1607          }
1608  
1609 <        private class DescendingKeySetView extends AbstractSet<K> {
1610 <            public Iterator<K> iterator() {
1611 <                return new Iterator<K>() {
1612 <                    private Iterator<Entry<K,V>> i = descendingEntrySet().iterator();
1609 >        final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1610 >            SubMapEntryIterator(TreeMap.Entry<K,V> first,
1611 >                                TreeMap.Entry<K,V> firstExcluded) {
1612 >                super(first, firstExcluded);
1613 >            }
1614 >            public Map.Entry<K,V> next() {
1615 >                return nextEntry();
1616 >            }
1617 >        }
1618  
1619 <                    public boolean hasNext() { return i.hasNext(); }
1620 <                    public K next() { return i.next().getKey(); }
1621 <                    public void remove() { i.remove(); }
1622 <                };
1619 >        final class SubMapKeyIterator extends SubMapIterator<K> {
1620 >            SubMapKeyIterator(TreeMap.Entry<K,V> first,
1621 >                              TreeMap.Entry<K,V> firstExcluded) {
1622 >                super(first, firstExcluded);
1623              }
1624 +            public K next() {
1625 +                return nextEntry().key;
1626 +            }
1627 +        }
1628  
1629 <            public int size() {
1630 <                return SubMap.this.size();
1629 >        final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1630 >            DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
1631 >                                          TreeMap.Entry<K,V> lastExcluded) {
1632 >                super(last, lastExcluded);
1633              }
1634  
1635 <            public boolean contains(Object k) {
1636 <                return SubMap.this.containsKey(k);
1635 >            public Map.Entry<K,V> next() {
1636 >                return prevEntry();
1637              }
1638          }
1639  
1640 <        public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1641 <            if (!inRange2(fromKey))
1640 >        final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
1641 >            DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
1642 >                                        TreeMap.Entry<K,V> lastExcluded) {
1643 >                super(last, lastExcluded);
1644 >            }
1645 >            public K next() {
1646 >                return prevEntry().key;
1647 >            }
1648 >        }
1649 >    }
1650 >
1651 >    static class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1652 >        private static final long serialVersionUID = 912986545866124060L;
1653 >
1654 >        AscendingSubMap(TreeMap<K,V> m,
1655 >                        boolean fromStart, K lo, int loExcluded,
1656 >                        boolean toEnd, K hi, int hiExcluded) {
1657 >            super(m, fromStart, lo, loExcluded, toEnd, hi, hiExcluded);
1658 >        }
1659 >
1660 >        public Comparator<? super K> comparator() {
1661 >            return m.comparator();
1662 >        }
1663 >
1664 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1665 >                                        K toKey, boolean toInclusive) {
1666 >            if (!inRange(fromKey, fromInclusive))
1667                  throw new IllegalArgumentException("fromKey out of range");
1668 <            if (!inRange2(toKey))
1668 >            if (!inRange(toKey, toInclusive))
1669                  throw new IllegalArgumentException("toKey out of range");
1670 <            return new SubMap(fromKey, toKey);
1670 >            return new AscendingSubMap(m,
1671 >                                       false, fromKey, excluded(fromInclusive),
1672 >                                       false, toKey,   excluded(toInclusive));
1673          }
1674  
1675 <        public NavigableMap<K,V> navigableHeadMap(K toKey) {
1676 <            if (!inRange2(toKey))
1675 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1676 >            if (!inClosedRange(toKey))
1677                  throw new IllegalArgumentException("toKey out of range");
1678 <            return new SubMap(fromStart, fromKey, false, toKey);
1678 >            return new AscendingSubMap(m,
1679 >                                       fromStart, lo,    loExcluded,
1680 >                                       false, toKey, excluded(inclusive));
1681          }
1682  
1683 <        public NavigableMap<K,V> navigableTailMap(K fromKey) {
1684 <            if (!inRange2(fromKey))
1683 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1684 >            if (!inRange(fromKey, inclusive))
1685                  throw new IllegalArgumentException("fromKey out of range");
1686 <            return new SubMap(false, fromKey, toEnd, toKey);
1686 >            return new AscendingSubMap(m,
1687 >                                       false, fromKey, excluded(inclusive),
1688 >                                       toEnd, hi,      hiExcluded);
1689          }
1690  
1691 <        public SortedMap<K,V> subMap(K fromKey, K toKey) {
1692 <            return navigableSubMap(fromKey, toKey);
1691 >        Iterator<K> keyIterator() {
1692 >            return new SubMapKeyIterator(loEntry(), hiFence());
1693          }
1694  
1695 <        public SortedMap<K,V> headMap(K toKey) {
1696 <            return navigableHeadMap(toKey);
1695 >        Iterator<K> descendingKeyIterator() {
1696 >            return new DescendingSubMapKeyIterator(hiEntry(), loFence());
1697          }
1698  
1699 <        public SortedMap<K,V> tailMap(K fromKey) {
1700 <            return navigableTailMap(fromKey);
1699 >        class AscendingEntrySetView extends NavigableSubMap.EntrySetView {
1700 >            public Iterator<Map.Entry<K,V>> iterator() {
1701 >                return new SubMapEntryIterator(loEntry(), hiFence());
1702 >            }
1703          }
1704  
1705 <        private boolean inRange(Object key) {
1706 <            return (fromStart || compare(key, fromKey) >= 0) &&
1707 <                   (toEnd     || compare(key, toKey)   <  0);
1705 >        public Set<Map.Entry<K,V>> entrySet() {
1706 >            EntrySetView es = entrySetView;
1707 >            return (es != null) ? es : new AscendingEntrySetView();
1708          }
1709  
1710 <        // This form allows the high endpoint (as well as all legit keys)
1711 <        private boolean inRange2(Object key) {
1396 <            return (fromStart || compare(key, fromKey) >= 0) &&
1397 <                   (toEnd     || compare(key, toKey)   <= 0);
1710 >        public K firstKey() {
1711 >            return key(loEntry());
1712          }
1399    }
1400
1401    /**
1402     * TreeMap Iterator.
1403     */
1404    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1405        int expectedModCount = TreeMap.this.modCount;
1406        Entry<K,V> lastReturned = null;
1407        Entry<K,V> next;
1713  
1714 <        PrivateEntryIterator(Entry<K,V> first) {
1715 <            next = first;
1714 >        public K lastKey() {
1715 >            return key(hiEntry());
1716          }
1717  
1718 <        public boolean hasNext() {
1719 <            return next != null;
1718 >        public Map.Entry<K,V> firstEntry() {
1719 >            return loEntry();
1720          }
1721  
1722 <        Entry<K,V> nextEntry() {
1723 <            if (next == null)
1419 <                throw new NoSuchElementException();
1420 <            if (modCount != expectedModCount)
1421 <                throw new ConcurrentModificationException();
1422 <            lastReturned = next;
1423 <            next = successor(next);
1424 <            return lastReturned;
1722 >        public Map.Entry<K,V> lastEntry() {
1723 >            return hiEntry();
1724          }
1725  
1726 <        public void remove() {
1727 <            if (lastReturned == null)
1429 <                throw new IllegalStateException();
1430 <            if (modCount != expectedModCount)
1431 <                throw new ConcurrentModificationException();
1432 <            if (lastReturned.left != null && lastReturned.right != null)
1433 <                next = lastReturned;
1434 <            deleteEntry(lastReturned);
1435 <            expectedModCount++;
1436 <            lastReturned = null;
1726 >        public Map.Entry<K,V> pollFirstEntry() {
1727 >            return pollLoEntry();
1728          }
1438    }
1729  
1730 <    class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1731 <        EntryIterator(Entry<K,V> first) {
1442 <            super(first);
1730 >        public Map.Entry<K,V> pollLastEntry() {
1731 >            return pollHiEntry();
1732          }
1733 <        public Map.Entry<K,V> next() {
1734 <            return nextEntry();
1733 >
1734 >        public NavigableMap<K,V> descendingMap() {
1735 >            NavigableMap<K,V> mv = descendingMapView;
1736 >            return (mv != null) ? mv :
1737 >                (descendingMapView =
1738 >                 new DescendingSubMap(m,
1739 >                                      fromStart, lo, loExcluded,
1740 >                                      toEnd, hi, hiExcluded));
1741          }
1742      }
1743  
1744 <    class KeyIterator extends PrivateEntryIterator<K> {
1745 <        KeyIterator(Entry<K,V> first) {
1746 <            super(first);
1744 >    static class DescendingSubMap<K,V> extends NavigableSubMap<K,V> {
1745 >        private static final long serialVersionUID = 912986545866120460L;
1746 >        DescendingSubMap(TreeMap<K,V> m,
1747 >                        boolean fromStart, K lo, int loExcluded,
1748 >                        boolean toEnd, K hi, int hiExcluded) {
1749 >            super(m, fromStart, lo, loExcluded, toEnd, hi, hiExcluded);
1750          }
1751 <        public K next() {
1752 <            return nextEntry().key;
1751 >
1752 >        private final Comparator<? super K> reverseComparator =
1753 >            Collections.reverseOrder(m.comparator);
1754 >
1755 >        public Comparator<? super K> comparator() {
1756 >            return reverseComparator;
1757          }
1456    }
1758  
1759 <    class ValueIterator extends PrivateEntryIterator<V> {
1760 <        ValueIterator(Entry<K,V> first) {
1761 <            super(first);
1759 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1760 >                                        K toKey, boolean toInclusive) {
1761 >            if (!inRange(fromKey, fromInclusive))
1762 >                throw new IllegalArgumentException("fromKey out of range");
1763 >            if (!inRange(toKey, toInclusive))
1764 >                throw new IllegalArgumentException("toKey out of range");
1765 >            return new DescendingSubMap(m,
1766 >                                        false, toKey,   excluded(toInclusive),
1767 >                                        false, fromKey, excluded(fromInclusive));
1768          }
1769 <        public V next() {
1770 <            return nextEntry().value;
1769 >
1770 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1771 >            if (!inRange(toKey, inclusive))
1772 >                throw new IllegalArgumentException("toKey out of range");
1773 >            return new DescendingSubMap(m,
1774 >                                        false, toKey, excluded(inclusive),
1775 >                                        toEnd, hi, hiExcluded);
1776          }
1465    }
1777  
1778 <    class SubMapEntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1779 <        private final K firstExcludedKey;
1778 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1779 >            if (!inRange(fromKey, inclusive))
1780 >                throw new IllegalArgumentException("fromKey out of range");
1781 >            return new DescendingSubMap(m,
1782 >                                        fromStart, lo,      loExcluded,
1783 >                                        false, fromKey, excluded(inclusive));
1784 >        }
1785  
1786 <        SubMapEntryIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1787 <            super(first);
1472 <            firstExcludedKey = (firstExcluded == null
1473 <                                ? null
1474 <                                : firstExcluded.key);
1786 >        Iterator<K> keyIterator() {
1787 >            return new DescendingSubMapKeyIterator(hiEntry(), loFence());
1788          }
1789  
1790 <        public boolean hasNext() {
1791 <            return next != null && next.key != firstExcludedKey;
1790 >        Iterator<K> descendingKeyIterator() {
1791 >            return new SubMapKeyIterator(loEntry(), hiFence());
1792          }
1793  
1794 <        public Map.Entry<K,V> next() {
1795 <            if (next == null || next.key == firstExcludedKey)
1796 <                throw new NoSuchElementException();
1797 <            return nextEntry();
1794 >        class DescendingEntrySetView extends NavigableSubMap.EntrySetView {
1795 >            public Iterator<Map.Entry<K,V>> iterator() {
1796 >                return new DescendingSubMapEntryIterator(hiEntry(), loFence());
1797 >            }
1798          }
1486    }
1799  
1800 <    /**
1801 <     * Base for Descending Iterators.
1802 <     */
1491 <    abstract class DescendingPrivateEntryIterator<T> extends PrivateEntryIterator<T> {
1492 <        DescendingPrivateEntryIterator(Entry<K,V> first) {
1493 <            super(first);
1800 >        public Set<Map.Entry<K,V>> entrySet() {
1801 >            EntrySetView es = entrySetView;
1802 >            return (es != null) ? es : new DescendingEntrySetView();
1803          }
1804  
1805 <        Entry<K,V> nextEntry() {
1806 <            if (next == null)
1498 <                throw new NoSuchElementException();
1499 <            if (modCount != expectedModCount)
1500 <                throw new ConcurrentModificationException();
1501 <            lastReturned = next;
1502 <            next = predecessor(next);
1503 <            return lastReturned;
1805 >        public K firstKey() {
1806 >            return key(hiEntry());
1807          }
1505    }
1808  
1809 <    class DescendingEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1810 <        DescendingEntryIterator(Entry<K,V> first) {
1509 <            super(first);
1809 >        public K lastKey() {
1810 >            return key(loEntry());
1811          }
1812 <        public Map.Entry<K,V> next() {
1813 <            return nextEntry();
1812 >
1813 >        public Map.Entry<K,V> firstEntry() {
1814 >            return hiEntry();
1815          }
1514    }
1816  
1817 <    class DescendingKeyIterator extends DescendingPrivateEntryIterator<K> {
1818 <        DescendingKeyIterator(Entry<K,V> first) {
1518 <            super(first);
1817 >        public Map.Entry<K,V> lastEntry() {
1818 >            return loEntry();
1819          }
1820 <        public K next() {
1821 <            return nextEntry().key;
1820 >
1821 >        public Map.Entry<K,V> pollFirstEntry() {
1822 >            return pollHiEntry();
1823          }
1523    }
1824  
1825 +        public Map.Entry<K,V> pollLastEntry() {
1826 +            return pollLoEntry();
1827 +        }
1828  
1829 <    class DescendingSubMapEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1830 <        private final K lastExcludedKey;
1829 >        public NavigableMap<K,V> descendingMap() {
1830 >            NavigableMap<K,V> mv = descendingMapView;
1831 >            return (mv != null) ? mv :
1832 >                (descendingMapView =
1833 >                 new AscendingSubMap(m,
1834 >                                     fromStart, lo, loExcluded,
1835 >                                     toEnd, hi, hiExcluded));
1836 >        }
1837  
1838 <        DescendingSubMapEntryIterator(Entry<K,V> last, Entry<K,V> lastExcluded) {
1839 <            super(last);
1531 <            lastExcludedKey = (lastExcluded == null
1532 <                                ? null
1533 <                                : lastExcluded.key);
1838 >        @Override TreeMap.Entry<K,V> subCeiling(K key) {
1839 >            return super.subFloor(key);
1840          }
1841  
1842 <        public boolean hasNext() {
1843 <            return next != null && next.key != lastExcludedKey;
1842 >        @Override TreeMap.Entry<K,V> subHigher(K key) {
1843 >            return super.subLower(key);
1844          }
1845  
1846 <        public Map.Entry<K,V> next() {
1847 <            if (next == null || next.key == lastExcludedKey)
1542 <                throw new NoSuchElementException();
1543 <            return nextEntry();
1846 >        @Override TreeMap.Entry<K,V> subFloor(K key) {
1847 >            return super.subCeiling(key);
1848          }
1849  
1850 +        @Override TreeMap.Entry<K,V> subLower(K key) {
1851 +            return super.subHigher(key);
1852 +        }
1853      }
1854  
1855      /**
1856       * Compares two keys using the correct comparison method for this TreeMap.
1857       */
1858 <    private int compare(Object k1, Object k2) {
1858 >    final int compare(Object k1, Object k2) {
1859          return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1860 <                                : comparator.compare((K)k1, (K)k2);
1860 >            : comparator.compare((K)k1, (K)k2);
1861      }
1862  
1863      /**
1864       * Test two values for equality.  Differs from o1.equals(o2) only in
1865       * that it copes with <tt>null</tt> o1 properly.
1866       */
1867 <    private static boolean valEquals(Object o1, Object o2) {
1867 >    final static boolean valEquals(Object o1, Object o2) {
1868          return (o1==null ? o2==null : o1.equals(o2));
1869      }
1870  
1871 +    /**
1872 +     * This class exists solely for the sake of serialization
1873 +     * compatibility with previous releases of TreeMap that did not
1874 +     * support NavigableMap.  It translates an old-version SubMap into
1875 +     * a new-version AscendingSubMap. This class is never otherwise
1876 +     * used.
1877 +     */
1878 +    private class SubMap extends AbstractMap<K,V>
1879 +        implements SortedMap<K,V>, java.io.Serializable {
1880 +        private static final long serialVersionUID = -6520786458950516097L;
1881 +        private boolean fromStart = false, toEnd = false;
1882 +        private K fromKey, toKey;
1883 +        private Object readResolve() {
1884 +            return new AscendingSubMap(TreeMap.this,
1885 +                                       fromStart, fromKey, 0,
1886 +                                       toEnd, toKey, 1);
1887 +        }
1888 +        public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
1889 +        public K lastKey() { throw new InternalError(); }
1890 +        public K firstKey() { throw new InternalError(); }
1891 +        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
1892 +        public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
1893 +        public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
1894 +        public Comparator<? super K> comparator() { throw new InternalError(); }
1895 +    }
1896 +
1897 +
1898      private static final boolean RED   = false;
1899      private static final boolean BLACK = true;
1900  
# Line 1569 | Line 1903 | public class TreeMap<K,V>
1903       * user (see Map.Entry).
1904       */
1905  
1906 <    static class Entry<K,V> implements Map.Entry<K,V> {
1906 >    static final class Entry<K,V> implements Map.Entry<K,V> {
1907          K key;
1908          V value;
1909          Entry<K,V> left = null;
# Line 1641 | Line 1975 | public class TreeMap<K,V>
1975       * Returns the first Entry in the TreeMap (according to the TreeMap's
1976       * key-sort function).  Returns null if the TreeMap is empty.
1977       */
1978 <    private Entry<K,V> getFirstEntry() {
1978 >    final Entry<K,V> getFirstEntry() {
1979          Entry<K,V> p = root;
1980          if (p != null)
1981              while (p.left != null)
# Line 1653 | Line 1987 | public class TreeMap<K,V>
1987       * Returns the last Entry in the TreeMap (according to the TreeMap's
1988       * key-sort function).  Returns null if the TreeMap is empty.
1989       */
1990 <    private Entry<K,V> getLastEntry() {
1990 >    final Entry<K,V> getLastEntry() {
1991          Entry<K,V> p = root;
1992          if (p != null)
1993              while (p.right != null)
# Line 1664 | Line 1998 | public class TreeMap<K,V>
1998      /**
1999       * Returns the successor of the specified Entry, or null if no such.
2000       */
2001 <    private Entry<K,V> successor(Entry<K,V> t) {
2001 >    final Entry<K,V> successor(Entry<K,V> t) {
2002          if (t == null)
2003              return null;
2004          else if (t.right != null) {
# Line 1686 | Line 2020 | public class TreeMap<K,V>
2020      /**
2021       * Returns the predecessor of the specified Entry, or null if no such.
2022       */
2023 <    private Entry<K,V> predecessor(Entry<K,V> t) {
2023 >    final Entry<K,V> predecessor(Entry<K,V> t) {
2024          if (t == null)
2025              return null;
2026          else if (t.left != null) {
# Line 1957 | Line 2291 | public class TreeMap<K,V>
2291          }
2292      }
2293  
1960
1961
2294      /**
2295       * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e.,
2296       * deserialize it).
# Line 2020 | Line 2352 | public class TreeMap<K,V>
2352       * @throws ClassNotFoundException propagated from readObject.
2353       *         This cannot occur if str is null.
2354       */
2355 <    private
2356 <    void buildFromSorted(int size, Iterator it,
2357 <                         java.io.ObjectInputStream str,
2026 <                         V defaultVal)
2355 >    private void buildFromSorted(int size, Iterator it,
2356 >                                 java.io.ObjectInputStream str,
2357 >                                 V defaultVal)
2358          throws  java.io.IOException, ClassNotFoundException {
2359          this.size = size;
2360 <        root =
2361 <            buildFromSorted(0, 0, size-1, computeRedLevel(size),
2031 <                            it, str, defaultVal);
2360 >        root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
2361 >                               it, str, defaultVal);
2362      }
2363  
2364      /**
2365       * Recursive "helper method" that does the real work of the
2366 <     * of the previous method.  Identically named parameters have
2366 >     * previous method.  Identically named parameters have
2367       * identical definitions.  Additional parameters are documented below.
2368       * It is assumed that the comparator and size fields of the TreeMap are
2369       * already set prior to calling this method.  (It ignores both fields.)

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines