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.23 by jsr166, Mon Jul 18 01:14:34 2005 UTC vs.
Revision 1.36 by jsr166, Tue May 9 16:35:40 2006 UTC

# Line 1 | Line 1
1   /*
2   * %W% %E%
3   *
4 < * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
4 > * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5   * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6   */
7  
8   package java.util;
9 import java.util.*; // for javadoc (till 6280605 is fixed)
9  
10   /**
11   * A Red-Black tree based {@link NavigableMap} implementation.
# Line 69 | Line 68 | import java.util.*; // for javadoc (till
68   * associated map using <tt>put</tt>.)
69   *
70   * <p>This class is a member of the
71 < * <a href="{@docRoot}/../guide/collections/index.html">
71 > * <a href="{@docRoot}/../technotes/guides/collections/index.html">
72   * Java Collections Framework</a>.
73   *
74   * @param <K> the type of keys maintained by this map
# Line 96 | Line 95 | public class TreeMap<K,V>
95       *
96       * @serial
97       */
98 <    private Comparator<? super K> comparator = null;
98 >    private final Comparator<? super K> comparator;
99  
100      private transient Entry<K,V> root = null;
101  
# Line 110 | Line 109 | public class TreeMap<K,V>
109       */
110      private transient int modCount = 0;
111  
113    private void incrementSize()   { modCount++; size++; }
114    private void decrementSize()   { modCount++; size--; }
115
112      /**
113       * Constructs a new, empty tree map, using the natural ordering of its
114       * keys.  All keys inserted into the map must implement the {@link
# Line 126 | Line 122 | public class TreeMap<K,V>
122       * <tt>ClassCastException</tt>.
123       */
124      public TreeMap() {
125 +        comparator = null;
126      }
127  
128      /**
# Line 161 | Line 158 | public class TreeMap<K,V>
158       * @throws NullPointerException if the specified map is null
159       */
160      public TreeMap(Map<? extends K, ? extends V> m) {
161 +        comparator = null;
162          putAll(m);
163      }
164  
# Line 225 | 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 <    }
232 <
233 <    private boolean valueSearchNull(Entry n) {
234 <        if (n.value == null)
235 <            return true;
236 <
237 <        // Check left and right subtrees for value
238 <        return (n.left  != null && valueSearchNull(n.left)) ||
239 <               (n.right != null && valueSearchNull(n.right));
240 <    }
241 <
242 <    private boolean valueSearchNonNull(Entry n, Object value) {
243 <        // Check this node for the value
244 <        if (value.equals(n.value))
245 <            return true;
246 <
247 <        // Check left and right subtrees for value
248 <        return (n.left  != null && valueSearchNonNull(n.left, value)) ||
249 <               (n.right != null && valueSearchNonNull(n.right, value));
226 >        for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
227 >            if (valEquals(value, e.value))
228 >                return true;
229 >        return false;
230      }
231  
232      /**
233 <     * Returns the value to which this map maps the specified key, or
234 <     * <tt>null</tt> if the map contains no mapping for the key.  A return
235 <     * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
236 <     * map contains no mapping for the key; it's also possible that the map
237 <     * explicitly maps the key to <tt>null</tt>.  The {@link #containsKey
238 <     * containsKey} operation may be used to distinguish these two cases.
233 >     * Returns the value to which the specified key is mapped,
234 >     * or {@code null} if this map contains no mapping for the key.
235 >     *
236 >     * <p>More formally, if this map contains a mapping from a key
237 >     * {@code k} to a value {@code v} such that {@code key} compares
238 >     * equal to {@code k} according to the map's ordering, then this
239 >     * method returns {@code v}; otherwise it returns {@code null}.
240 >     * (There can be at most one such mapping.)
241 >     *
242 >     * <p>A return value of {@code null} does not <i>necessarily</i>
243 >     * indicate that the map contains no mapping for the key; it's also
244 >     * possible that the map explicitly maps the key to {@code null}.
245 >     * The {@link #containsKey containsKey} operation may be used to
246 >     * distinguish these two cases.
247       *
260     * @param key key whose associated value is to be returned
261     * @return the value to which this map maps the specified key, or
262     *         <tt>null</tt> if the map contains no mapping for the key
248       * @throws ClassCastException if the specified key cannot be compared
249       *         with the keys currently in the map
250       * @throws NullPointerException if the specified key is null
# Line 331 | Line 316 | public class TreeMap<K,V>
316       *         and this map uses natural ordering, or its comparator
317       *         does not permit null keys
318       */
319 <    private Entry<K,V> getEntry(Object key) {
319 >    final Entry<K,V> getEntry(Object key) {
320          // Offload comparator-based version for sake of performance
321          if (comparator != null)
322              return getEntryUsingComparator(key);
323 +        if (key == null)
324 +            throw new NullPointerException();
325          Comparable<? super K> k = (Comparable<? super K>) key;
326          Entry<K,V> p = root;
327          while (p != null) {
# Line 355 | 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 377 | 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)
383 <            return null;
384 <
385 <        while (true) {
371 >        while (p != null) {
372              int cmp = compare(key, p.key);
373              if (cmp < 0) {
374                  if (p.left != null)
# Line 404 | Line 390 | public class TreeMap<K,V>
390              } else
391                  return p;
392          }
393 +        return null;
394      }
395  
396      /**
# Line 411 | 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)
417 <            return null;
418 <
419 <        while (true) {
403 >        while (p != null) {
404              int cmp = compare(key, p.key);
405              if (cmp > 0) {
406                  if (p.right != null)
# Line 439 | Line 423 | public class TreeMap<K,V>
423                  return p;
424  
425          }
426 +        return null;
427      }
428  
429      /**
# Line 447 | 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)
453 <            return null;
454 <
455 <        while (true) {
437 >        while (p != null) {
438              int cmp = compare(key, p.key);
439              if (cmp < 0) {
440                  if (p.left != null)
# Line 473 | Line 455 | public class TreeMap<K,V>
455                  }
456              }
457          }
458 +        return null;
459      }
460  
461      /**
# Line 480 | 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)
486 <            return null;
487 <
488 <        while (true) {
468 >        while (p != null) {
469              int cmp = compare(key, p.key);
470              if (cmp > 0) {
471                  if (p.right != null)
# Line 506 | Line 486 | public class TreeMap<K,V>
486                  }
487              }
488          }
489 <    }
510 <
511 <    /**
512 <     * Returns the key corresponding to the specified Entry.
513 <     * @throws NoSuchElementException if the Entry is null
514 <     */
515 <    private static <K> K key(Entry<K,?> e) {
516 <        if (e==null)
517 <            throw new NoSuchElementException();
518 <        return e.key;
489 >        return null;
490      }
491  
492      /**
# Line 538 | Line 509 | public class TreeMap<K,V>
509       */
510      public V put(K key, V value) {
511          Entry<K,V> t = root;
541
512          if (t == null) {
513 <            // TBD
514 < //             if (key == null) {
515 < //                 if (comparator == null)
516 < //                     throw new NullPointerException();
517 < //                 comparator.compare(key, key);
548 < //             }
549 <            incrementSize();
513 >            // TBD:
514 >            // 5045147: (coll) Adding null to an empty TreeSet should
515 >            // throw NullPointerException
516 >            //
517 >            // compare(key, key); // type check
518              root = new Entry<K,V>(key, value, null);
519 +            size = 1;
520 +            modCount++;
521              return null;
522          }
523 <
524 <        while (true) {
525 <            int cmp = compare(key, t.key);
526 <            if (cmp == 0) {
527 <                return t.setValue(value);
528 <            } else if (cmp < 0) {
529 <                if (t.left != null) {
523 >        int cmp;
524 >        Entry<K,V> parent;
525 >        // split comparator and comparable paths
526 >        Comparator<? super K> cpr = comparator;
527 >        if (cpr != null) {
528 >            do {
529 >                parent = t;
530 >                cmp = cpr.compare(key, t.key);
531 >                if (cmp < 0)
532                      t = t.left;
533 <                } else {
562 <                    incrementSize();
563 <                    t.left = new Entry<K,V>(key, value, t);
564 <                    fixAfterInsertion(t.left);
565 <                    return null;
566 <                }
567 <            } else { // cmp > 0
568 <                if (t.right != null) {
533 >                else if (cmp > 0)
534                      t = t.right;
535 <                } else {
536 <                    incrementSize();
537 <                    t.right = new Entry<K,V>(key, value, t);
573 <                    fixAfterInsertion(t.right);
574 <                    return null;
575 <                }
576 <            }
535 >                else
536 >                    return t.setValue(value);
537 >            } while (t != null);
538          }
539 +        else {
540 +            if (key == null)
541 +                throw new NullPointerException();
542 +            Comparable<? super K> k = (Comparable<? super K>) key;
543 +            do {
544 +                parent = t;
545 +                cmp = k.compareTo(t.key);
546 +                if (cmp < 0)
547 +                    t = t.left;
548 +                else if (cmp > 0)
549 +                    t = t.right;
550 +                else
551 +                    return t.setValue(value);
552 +            } while (t != null);
553 +        }
554 +        Entry<K,V> e = new Entry<K,V>(key, value, parent);
555 +        if (cmp < 0)
556 +            parent.left = e;
557 +        else
558 +            parent.right = e;
559 +        fixAfterInsertion(e);
560 +        size++;
561 +        modCount++;
562 +        return null;
563      }
564  
565      /**
# Line 630 | Line 615 | public class TreeMap<K,V>
615          clone.size = 0;
616          clone.modCount = 0;
617          clone.entrySet = null;
618 <        clone.descendingEntrySet = null;
619 <        clone.descendingKeySet = null;
618 >        clone.navigableKeySet = null;
619 >        clone.descendingMap = null;
620  
621          // Initialize clone with our mappings
622          try {
# Line 649 | Line 634 | public class TreeMap<K,V>
634       * @since 1.6
635       */
636      public Map.Entry<K,V> firstEntry() {
637 <        Entry<K,V> e = getFirstEntry();
653 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
637 >        return exportEntry(getFirstEntry());
638      }
639  
640      /**
641       * @since 1.6
642       */
643      public Map.Entry<K,V> lastEntry() {
644 <        Entry<K,V> e = getLastEntry();
661 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
644 >        return exportEntry(getLastEntry());
645      }
646  
647      /**
# Line 666 | Line 649 | public class TreeMap<K,V>
649       */
650      public Map.Entry<K,V> pollFirstEntry() {
651          Entry<K,V> p = getFirstEntry();
652 <        if (p == null)
653 <            return null;
654 <        Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(p);
672 <        deleteEntry(p);
652 >        Map.Entry<K,V> result = exportEntry(p);
653 >        if (p != null)
654 >            deleteEntry(p);
655          return result;
656      }
657  
# Line 678 | Line 660 | public class TreeMap<K,V>
660       */
661      public Map.Entry<K,V> pollLastEntry() {
662          Entry<K,V> p = getLastEntry();
663 <        if (p == null)
664 <            return null;
665 <        Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(p);
684 <        deleteEntry(p);
663 >        Map.Entry<K,V> result = exportEntry(p);
664 >        if (p != null)
665 >            deleteEntry(p);
666          return result;
667      }
668  
# Line 693 | Line 674 | public class TreeMap<K,V>
674       * @since 1.6
675       */
676      public Map.Entry<K,V> lowerEntry(K key) {
677 <        Entry<K,V> e =  getLowerEntry(key);
697 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
677 >        return exportEntry(getLowerEntry(key));
678      }
679  
680      /**
# Line 705 | Line 685 | public class TreeMap<K,V>
685       * @since 1.6
686       */
687      public K lowerKey(K key) {
688 <        Entry<K,V> e =  getLowerEntry(key);
709 <        return (e == null)? null : e.key;
688 >        return keyOrNull(getLowerEntry(key));
689      }
690  
691      /**
# Line 717 | Line 696 | public class TreeMap<K,V>
696       * @since 1.6
697       */
698      public Map.Entry<K,V> floorEntry(K key) {
699 <        Entry<K,V> e = getFloorEntry(key);
721 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
699 >        return exportEntry(getFloorEntry(key));
700      }
701  
702      /**
# Line 729 | Line 707 | public class TreeMap<K,V>
707       * @since 1.6
708       */
709      public K floorKey(K key) {
710 <        Entry<K,V> e = getFloorEntry(key);
733 <        return (e == null)? null : e.key;
710 >        return keyOrNull(getFloorEntry(key));
711      }
712  
713      /**
# Line 741 | Line 718 | public class TreeMap<K,V>
718       * @since 1.6
719       */
720      public Map.Entry<K,V> ceilingEntry(K key) {
721 <        Entry<K,V> e = getCeilingEntry(key);
745 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
721 >        return exportEntry(getCeilingEntry(key));
722      }
723  
724      /**
# Line 753 | Line 729 | public class TreeMap<K,V>
729       * @since 1.6
730       */
731      public K ceilingKey(K key) {
732 <        Entry<K,V> e = getCeilingEntry(key);
757 <        return (e == null)? null : e.key;
732 >        return keyOrNull(getCeilingEntry(key));
733      }
734  
735      /**
# Line 765 | Line 740 | public class TreeMap<K,V>
740       * @since 1.6
741       */
742      public Map.Entry<K,V> higherEntry(K key) {
743 <        Entry<K,V> e = getHigherEntry(key);
769 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
743 >        return exportEntry(getHigherEntry(key));
744      }
745  
746      /**
# Line 777 | Line 751 | public class TreeMap<K,V>
751       * @since 1.6
752       */
753      public K higherKey(K key) {
754 <        Entry<K,V> e = getHigherEntry(key);
781 <        return (e == null)? null : e.key;
754 >        return keyOrNull(getHigherEntry(key));
755      }
756  
757      // Views
# Line 788 | Line 761 | public class TreeMap<K,V>
761       * the first time this view is requested.  Views are stateless, so
762       * there's no reason to create more than one.
763       */
764 <    private transient Set<Map.Entry<K,V>> entrySet = null;
765 <    private transient Set<Map.Entry<K,V>> descendingEntrySet = null;
766 <    private transient Set<K> descendingKeySet = null;
764 >    private transient EntrySet entrySet = null;
765 >    private transient KeySet<K> navigableKeySet = null;
766 >    private transient NavigableMap<K,V> descendingMap = null;
767  
768      /**
769       * Returns a {@link Set} view of the keys contained in this map.
# Line 807 | Line 780 | public class TreeMap<K,V>
780       * operations.
781       */
782      public Set<K> keySet() {
783 <        Set<K> ks = keySet;
811 <        return (ks != null) ? ks : (keySet = new KeySet());
783 >        return navigableKeySet();
784      }
785  
786 <    class KeySet extends AbstractSet<K> {
787 <        public Iterator<K> iterator() {
788 <            return new KeyIterator(getFirstEntry());
789 <        }
790 <
791 <        public int size() {
792 <            return TreeMap.this.size();
821 <        }
822 <
823 <        public boolean contains(Object o) {
824 <            return containsKey(o);
825 <        }
826 <
827 <        public boolean remove(Object o) {
828 <            int oldSize = size;
829 <            TreeMap.this.remove(o);
830 <            return size != oldSize;
831 <        }
786 >    /**
787 >     * @since 1.6
788 >     */
789 >    public NavigableSet<K> navigableKeySet() {
790 >        KeySet<K> nks = navigableKeySet;
791 >        return (nks != null) ? nks : (navigableKeySet = new KeySet(this));
792 >    }
793  
794 <        public void clear() {
795 <            TreeMap.this.clear();
796 <        }
794 >    /**
795 >     * @since 1.6
796 >     */
797 >    public NavigableSet<K> descendingKeySet() {
798 >        return descendingMap().navigableKeySet();
799      }
800  
801      /**
# Line 855 | Line 818 | public class TreeMap<K,V>
818          return (vs != null) ? vs : (values = new Values());
819      }
820  
821 +    /**
822 +     * Returns a {@link Set} view of the mappings contained in this map.
823 +     * The set's iterator returns the entries in ascending key order.
824 +     * The set is backed by the map, so changes to the map are
825 +     * reflected in the set, and vice-versa.  If the map is modified
826 +     * while an iteration over the set is in progress (except through
827 +     * the iterator's own <tt>remove</tt> operation, or through the
828 +     * <tt>setValue</tt> operation on a map entry returned by the
829 +     * iterator) the results of the iteration are undefined.  The set
830 +     * supports element removal, which removes the corresponding
831 +     * mapping from the map, via the <tt>Iterator.remove</tt>,
832 +     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
833 +     * <tt>clear</tt> operations.  It does not support the
834 +     * <tt>add</tt> or <tt>addAll</tt> operations.
835 +     */
836 +    public Set<Map.Entry<K,V>> entrySet() {
837 +        EntrySet es = entrySet;
838 +        return (es != null) ? es : (entrySet = new EntrySet());
839 +    }
840 +
841 +    /**
842 +     * @since 1.6
843 +     */
844 +    public NavigableMap<K, V> descendingMap() {
845 +        NavigableMap<K, V> km = descendingMap;
846 +        return (km != null) ? km :
847 +            (descendingMap = new DescendingSubMap(this,
848 +                                                  true, null, true,
849 +                                                  true, null, true));
850 +    }
851 +
852 +    /**
853 +     * @throws ClassCastException       {@inheritDoc}
854 +     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
855 +     *         null and this map uses natural ordering, or its comparator
856 +     *         does not permit null keys
857 +     * @throws IllegalArgumentException {@inheritDoc}
858 +     * @since 1.6
859 +     */
860 +    public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
861 +                                    K toKey,   boolean toInclusive) {
862 +        return new AscendingSubMap(this,
863 +                                   false, fromKey, fromInclusive,
864 +                                   false, toKey,   toInclusive);
865 +    }
866 +
867 +    /**
868 +     * @throws ClassCastException       {@inheritDoc}
869 +     * @throws NullPointerException if <tt>toKey</tt> is null
870 +     *         and this map uses natural ordering, or its comparator
871 +     *         does not permit null keys
872 +     * @throws IllegalArgumentException {@inheritDoc}
873 +     * @since 1.6
874 +     */
875 +    public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
876 +        return new AscendingSubMap(this,
877 +                                   true,  null,  true,
878 +                                   false, toKey, inclusive);
879 +    }
880 +
881 +    /**
882 +     * @throws ClassCastException       {@inheritDoc}
883 +     * @throws NullPointerException if <tt>fromKey</tt> is null
884 +     *         and this map uses natural ordering, or its comparator
885 +     *         does not permit null keys
886 +     * @throws IllegalArgumentException {@inheritDoc}
887 +     * @since 1.6
888 +     */
889 +    public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) {
890 +        return new AscendingSubMap(this,
891 +                                   false, fromKey, inclusive,
892 +                                   true,  null,    true);
893 +    }
894 +
895 +    /**
896 +     * @throws ClassCastException       {@inheritDoc}
897 +     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
898 +     *         null and this map uses natural ordering, or its comparator
899 +     *         does not permit null keys
900 +     * @throws IllegalArgumentException {@inheritDoc}
901 +     */
902 +    public SortedMap<K,V> subMap(K fromKey, K toKey) {
903 +        return subMap(fromKey, true, toKey, false);
904 +    }
905 +
906 +    /**
907 +     * @throws ClassCastException       {@inheritDoc}
908 +     * @throws NullPointerException if <tt>toKey</tt> is null
909 +     *         and this map uses natural ordering, or its comparator
910 +     *         does not permit null keys
911 +     * @throws IllegalArgumentException {@inheritDoc}
912 +     */
913 +    public SortedMap<K,V> headMap(K toKey) {
914 +        return headMap(toKey, false);
915 +    }
916 +
917 +    /**
918 +     * @throws ClassCastException       {@inheritDoc}
919 +     * @throws NullPointerException if <tt>fromKey</tt> is null
920 +     *         and this map uses natural ordering, or its comparator
921 +     *         does not permit null keys
922 +     * @throws IllegalArgumentException {@inheritDoc}
923 +     */
924 +    public SortedMap<K,V> tailMap(K fromKey) {
925 +        return tailMap(fromKey, true);
926 +    }
927 +
928 +    // View class support
929 +
930      class Values extends AbstractCollection<V> {
931          public Iterator<V> iterator() {
932              return new ValueIterator(getFirstEntry());
# Line 865 | Line 937 | public class TreeMap<K,V>
937          }
938  
939          public boolean contains(Object o) {
940 <            for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e))
869 <                if (valEquals(e.getValue(), o))
870 <                    return true;
871 <            return false;
940 >            return TreeMap.this.containsValue(o);
941          }
942  
943          public boolean remove(Object o) {
# Line 886 | Line 955 | public class TreeMap<K,V>
955          }
956      }
957  
889    /**
890     * Returns a {@link Set} view of the mappings contained in this map.
891     * The set's iterator returns the entries in ascending key order.
892     * The set is backed by the map, so changes to the map are
893     * reflected in the set, and vice-versa.  If the map is modified
894     * while an iteration over the set is in progress (except through
895     * the iterator's own <tt>remove</tt> operation, or through the
896     * <tt>setValue</tt> operation on a map entry returned by the
897     * iterator) the results of the iteration are undefined.  The set
898     * supports element removal, which removes the corresponding
899     * mapping from the map, via the <tt>Iterator.remove</tt>,
900     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
901     * <tt>clear</tt> operations.  It does not support the
902     * <tt>add</tt> or <tt>addAll</tt> operations.
903     */
904    public Set<Map.Entry<K,V>> entrySet() {
905        Set<Map.Entry<K,V>> es = entrySet;
906        return (es != null) ? es : (entrySet = new EntrySet());
907    }
908
958      class EntrySet extends AbstractSet<Map.Entry<K,V>> {
959          public Iterator<Map.Entry<K,V>> iterator() {
960              return new EntryIterator(getFirstEntry());
# Line 942 | Line 991 | public class TreeMap<K,V>
991          }
992      }
993  
994 <    /**
995 <     * @since 1.6
994 >    /*
995 >     * Unlike Values and EntrySet, the KeySet class is static,
996 >     * delegating to a NavigableMap to allow use by SubMaps, which
997 >     * outweighs the ugliness of needing type-tests for the following
998 >     * Iterator methods that are defined appropriately in main versus
999 >     * submap classes.
1000       */
1001 <    public Set<Map.Entry<K,V>> descendingEntrySet() {
1002 <        Set<Map.Entry<K,V>> es = descendingEntrySet;
1003 <        return (es != null) ? es : (descendingEntrySet = new DescendingEntrySet());
1001 >
1002 >    Iterator<K> keyIterator() {
1003 >        return new KeyIterator(getFirstEntry());
1004      }
1005  
1006 <    class DescendingEntrySet extends EntrySet {
1007 <        public Iterator<Map.Entry<K,V>> iterator() {
1008 <            return new DescendingEntryIterator(getLastEntry());
1006 >    Iterator<K> descendingKeyIterator() {
1007 >        return new DescendingKeyIterator(getFirstEntry());
1008 >    }
1009 >
1010 >    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
1011 >        private final NavigableMap<E, Object> m;
1012 >        KeySet(NavigableMap<E,Object> map) { m = map; }
1013 >
1014 >        public Iterator<E> iterator() {
1015 >            if (m instanceof TreeMap)
1016 >                return ((TreeMap<E,Object>)m).keyIterator();
1017 >            else
1018 >                return (Iterator<E>)(((TreeMap.NavigableSubMap)m).keyIterator());
1019 >        }
1020 >
1021 >        public Iterator<E> descendingIterator() {
1022 >            if (m instanceof TreeMap)
1023 >                return ((TreeMap<E,Object>)m).descendingKeyIterator();
1024 >            else
1025 >                return (Iterator<E>)(((TreeMap.NavigableSubMap)m).descendingKeyIterator());
1026 >        }
1027 >
1028 >        public int size() { return m.size(); }
1029 >        public boolean isEmpty() { return m.isEmpty(); }
1030 >        public boolean contains(Object o) { return m.containsKey(o); }
1031 >        public void clear() { m.clear(); }
1032 >        public E lower(E e) { return m.lowerKey(e); }
1033 >        public E floor(E e) { return m.floorKey(e); }
1034 >        public E ceiling(E e) { return m.ceilingKey(e); }
1035 >        public E higher(E e) { return m.higherKey(e); }
1036 >        public E first() { return m.firstKey(); }
1037 >        public E last() { return m.lastKey(); }
1038 >        public Comparator<? super E> comparator() { return m.comparator(); }
1039 >        public E pollFirst() {
1040 >            Map.Entry<E,Object> e = m.pollFirstEntry();
1041 >            return e == null? null : e.getKey();
1042 >        }
1043 >        public E pollLast() {
1044 >            Map.Entry<E,Object> e = m.pollLastEntry();
1045 >            return e == null? null : e.getKey();
1046 >        }
1047 >        public boolean remove(Object o) {
1048 >            int oldSize = size();
1049 >            m.remove(o);
1050 >            return size() != oldSize;
1051 >        }
1052 >        public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
1053 >                                      E toElement,   boolean toInclusive) {
1054 >            return new TreeSet<E>(m.subMap(fromElement, fromInclusive,
1055 >                                           toElement,   toInclusive));
1056 >        }
1057 >        public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1058 >            return new TreeSet<E>(m.headMap(toElement, inclusive));
1059 >        }
1060 >        public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1061 >            return new TreeSet<E>(m.tailMap(fromElement, inclusive));
1062 >        }
1063 >        public SortedSet<E> subSet(E fromElement, E toElement) {
1064 >            return subSet(fromElement, true, toElement, false);
1065 >        }
1066 >        public SortedSet<E> headSet(E toElement) {
1067 >            return headSet(toElement, false);
1068 >        }
1069 >        public SortedSet<E> tailSet(E fromElement) {
1070 >            return tailSet(fromElement, true);
1071 >        }
1072 >        public NavigableSet<E> descendingSet() {
1073 >            return new TreeSet(m.descendingMap());
1074          }
1075      }
1076  
1077      /**
1078 <     * @since 1.6
1078 >     * Base class for TreeMap Iterators
1079       */
1080 <    public Set<K> descendingKeySet() {
1081 <        Set<K> ks = descendingKeySet;
1082 <        return (ks != null) ? ks : (descendingKeySet = new DescendingKeySet());
1080 >    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1081 >        Entry<K,V> next;
1082 >        Entry<K,V> lastReturned;
1083 >        int expectedModCount;
1084 >
1085 >        PrivateEntryIterator(Entry<K,V> first) {
1086 >            expectedModCount = modCount;
1087 >            lastReturned = null;
1088 >            next = first;
1089 >        }
1090 >
1091 >        public final boolean hasNext() {
1092 >            return next != null;
1093 >        }
1094 >
1095 >        final Entry<K,V> nextEntry() {
1096 >            Entry<K,V> e = lastReturned = next;
1097 >            if (e == null)
1098 >                throw new NoSuchElementException();
1099 >            if (modCount != expectedModCount)
1100 >                throw new ConcurrentModificationException();
1101 >            next = successor(e);
1102 >            return e;
1103 >        }
1104 >
1105 >        final Entry<K,V> prevEntry() {
1106 >            Entry<K,V> e = lastReturned= next;
1107 >            if (e == null)
1108 >                throw new NoSuchElementException();
1109 >            if (modCount != expectedModCount)
1110 >                throw new ConcurrentModificationException();
1111 >            next = predecessor(e);
1112 >            return e;
1113 >        }
1114 >
1115 >        public void remove() {
1116 >            if (lastReturned == null)
1117 >                throw new IllegalStateException();
1118 >            if (modCount != expectedModCount)
1119 >                throw new ConcurrentModificationException();
1120 >            if (lastReturned.left != null && lastReturned.right != null)
1121 >                next = lastReturned;
1122 >            deleteEntry(lastReturned);
1123 >            expectedModCount++;
1124 >            lastReturned = null;
1125 >        }
1126      }
1127  
1128 <    class DescendingKeySet extends KeySet {
1129 <        public Iterator<K> iterator() {
1130 <            return new DescendingKeyIterator(getLastEntry());
1128 >    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1129 >        EntryIterator(Entry<K,V> first) {
1130 >            super(first);
1131 >        }
1132 >        public Map.Entry<K,V> next() {
1133 >            return nextEntry();
1134          }
1135      }
1136  
1137 <    /**
1138 <     * @throws ClassCastException       {@inheritDoc}
1139 <     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
1140 <     *         null and this map uses natural ordering, or its comparator
1141 <     *         does not permit null keys
1142 <     * @throws IllegalArgumentException {@inheritDoc}
1143 <     * @since 1.6
1144 <     */
1145 <    public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1146 <        return new SubMap(fromKey, toKey);
1137 >    final class ValueIterator extends PrivateEntryIterator<V> {
1138 >        ValueIterator(Entry<K,V> first) {
1139 >            super(first);
1140 >        }
1141 >        public V next() {
1142 >            return nextEntry().value;
1143 >        }
1144 >    }
1145 >
1146 >    final class KeyIterator extends PrivateEntryIterator<K> {
1147 >        KeyIterator(Entry<K,V> first) {
1148 >            super(first);
1149 >        }
1150 >        public K next() {
1151 >            return nextEntry().key;
1152 >        }
1153      }
1154  
1155 +    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1156 +        DescendingKeyIterator(Entry<K,V> first) {
1157 +            super(first);
1158 +        }
1159 +        public K next() {
1160 +            return prevEntry().key;
1161 +        }
1162 +    }
1163 +
1164 +    // Little utilities
1165 +
1166      /**
1167 <     * @throws ClassCastException       {@inheritDoc}
987 <     * @throws NullPointerException if <tt>toKey</tt> is null
988 <     *         and this map uses natural ordering, or its comparator
989 <     *         does not permit null keys
990 <     * @throws IllegalArgumentException {@inheritDoc}
991 <     * @since 1.6
1167 >     * Compares two keys using the correct comparison method for this TreeMap.
1168       */
1169 <    public NavigableMap<K,V> navigableHeadMap(K toKey) {
1170 <        return new SubMap(toKey, true);
1169 >    final int compare(Object k1, Object k2) {
1170 >        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1171 >            : comparator.compare((K)k1, (K)k2);
1172      }
1173  
1174      /**
1175 <     * @throws ClassCastException       {@inheritDoc}
1176 <     * @throws NullPointerException if <tt>fromKey</tt> is null
1000 <     *         and this map uses natural ordering, or its comparator
1001 <     *         does not permit null keys
1002 <     * @throws IllegalArgumentException {@inheritDoc}
1003 <     * @since 1.6
1175 >     * Test two values for equality.  Differs from o1.equals(o2) only in
1176 >     * that it copes with <tt>null</tt> o1 properly.
1177       */
1178 <    public NavigableMap<K,V> navigableTailMap(K fromKey) {
1179 <        return new SubMap(fromKey, false);
1178 >    final static boolean valEquals(Object o1, Object o2) {
1179 >        return (o1==null ? o2==null : o1.equals(o2));
1180      }
1181  
1182      /**
1183 <     * Equivalent to {@link #navigableSubMap} but with a return type
1011 <     * conforming to the <tt>SortedMap</tt> interface.
1012 <     *
1013 <     * <p>{@inheritDoc}
1014 <     *
1015 <     * @throws ClassCastException       {@inheritDoc}
1016 <     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
1017 <     *         null and this map uses natural ordering, or its comparator
1018 <     *         does not permit null keys
1019 <     * @throws IllegalArgumentException {@inheritDoc}
1183 >     * Return SimpleImmutableEntry for entry, or null if null
1184       */
1185 <    public SortedMap<K,V> subMap(K fromKey, K toKey) {
1186 <        return new SubMap(fromKey, toKey);
1185 >    static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
1186 >        return e == null? null :
1187 >            new AbstractMap.SimpleImmutableEntry<K,V>(e);
1188      }
1189  
1190      /**
1191 <     * Equivalent to {@link #navigableHeadMap} but with a return type
1027 <     * conforming to the <tt>SortedMap</tt> interface.
1028 <     *
1029 <     * <p>{@inheritDoc}
1030 <     *
1031 <     * @throws ClassCastException       {@inheritDoc}
1032 <     * @throws NullPointerException if <tt>toKey</tt> is null
1033 <     *         and this map uses natural ordering, or its comparator
1034 <     *         does not permit null keys
1035 <     * @throws IllegalArgumentException {@inheritDoc}
1191 >     * Return key for entry, or null if null
1192       */
1193 <    public SortedMap<K,V> headMap(K toKey) {
1194 <        return new SubMap(toKey, true);
1193 >    static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
1194 >        return e == null? null : e.key;
1195      }
1196  
1197      /**
1198 <     * Equivalent to {@link #navigableTailMap} but with a return type
1199 <     * conforming to the <tt>SortedMap</tt> interface.
1044 <     *
1045 <     * <p>{@inheritDoc}
1046 <     *
1047 <     * @throws ClassCastException       {@inheritDoc}
1048 <     * @throws NullPointerException if <tt>fromKey</tt> is null
1049 <     *         and this map uses natural ordering, or its comparator
1050 <     *         does not permit null keys
1051 <     * @throws IllegalArgumentException {@inheritDoc}
1198 >     * Returns the key corresponding to the specified Entry.
1199 >     * @throws NoSuchElementException if the Entry is null
1200       */
1201 <    public SortedMap<K,V> tailMap(K fromKey) {
1202 <        return new SubMap(fromKey, false);
1201 >    static <K> K key(Entry<K,?> e) {
1202 >        if (e==null)
1203 >            throw new NoSuchElementException();
1204 >        return e.key;
1205      }
1206  
1057    private class SubMap
1058        extends AbstractMap<K,V>
1059        implements NavigableMap<K,V>, java.io.Serializable {
1060        private static final long serialVersionUID = -6520786458950516097L;
1207  
1208 +    // SubMaps
1209 +
1210 +    /**
1211 +     * @serial include
1212 +     */
1213 +    static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
1214 +        implements NavigableMap<K,V>, java.io.Serializable {
1215          /**
1216 <         * fromKey is significant only if fromStart is false.  Similarly,
1064 <         * toKey is significant only if toStart is false.
1216 >         * The backing map.
1217           */
1218 <        private boolean fromStart = false, toEnd = false;
1067 <        private K fromKey, toKey;
1068 <
1069 <        SubMap(K fromKey, K toKey) {
1070 <            if (compare(fromKey, toKey) > 0)
1071 <                throw new IllegalArgumentException("fromKey > toKey");
1072 <            this.fromKey = fromKey;
1073 <            this.toKey = toKey;
1074 <        }
1218 >        final TreeMap<K,V> m;
1219  
1220 <        SubMap(K key, boolean headMap) {
1221 <            compare(key, key); // Type-check key
1222 <
1223 <            if (headMap) {
1224 <                fromStart = true;
1225 <                toKey = key;
1220 >        /**
1221 >         * Endpoints are represented as triples (fromStart, lo,
1222 >         * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is
1223 >         * true, then the low (absolute) bound is the start of the
1224 >         * backing map, and the other values are ignored. Otherwise,
1225 >         * if loInclusive is true, lo is the inclusive bound, else lo
1226 >         * is the exclusive bound. Similarly for the upper bound.
1227 >         */
1228 >        final K lo, hi;
1229 >        final boolean fromStart, toEnd;
1230 >        final boolean loInclusive, hiInclusive;
1231 >
1232 >        NavigableSubMap(TreeMap<K,V> m,
1233 >                        boolean fromStart, K lo, boolean loInclusive,
1234 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1235 >            if (!fromStart && !toEnd) {
1236 >                if (m.compare(lo, hi) > 0)
1237 >                    throw new IllegalArgumentException("fromKey > toKey");
1238              } else {
1239 <                toEnd = true;
1240 <                fromKey = key;
1239 >                if (!fromStart) // type check
1240 >                    m.compare(lo, lo);
1241 >                if (!toEnd)
1242 >                    m.compare(hi, hi);
1243              }
1086        }
1244  
1245 <        SubMap(boolean fromStart, K fromKey, boolean toEnd, K toKey) {
1245 >            this.m = m;
1246              this.fromStart = fromStart;
1247 <            this.fromKey= fromKey;
1247 >            this.lo = lo;
1248 >            this.loInclusive = loInclusive;
1249              this.toEnd = toEnd;
1250 <            this.toKey = toKey;
1250 >            this.hi = hi;
1251 >            this.hiInclusive = hiInclusive;
1252 >        }
1253 >
1254 >        // internal utilities
1255 >
1256 >        final boolean tooLow(Object key) {
1257 >            if (!fromStart) {
1258 >                int c = m.compare(key, lo);
1259 >                if (c < 0 || (c == 0 && !loInclusive))
1260 >                    return true;
1261 >            }
1262 >            return false;
1263 >        }
1264 >
1265 >        final boolean tooHigh(Object key) {
1266 >            if (!toEnd) {
1267 >                int c = m.compare(key, hi);
1268 >                if (c > 0 || (c == 0 && !hiInclusive))
1269 >                    return true;
1270 >            }
1271 >            return false;
1272 >        }
1273 >
1274 >        final boolean inRange(Object key) {
1275 >            return !tooLow(key) && !tooHigh(key);
1276 >        }
1277 >
1278 >        final boolean inClosedRange(Object key) {
1279 >            return (fromStart || m.compare(key, lo) >= 0)
1280 >                && (toEnd || m.compare(hi, key) >= 0);
1281 >        }
1282 >
1283 >        final boolean inRange(Object key, boolean inclusive) {
1284 >            return inclusive ? inRange(key) : inClosedRange(key);
1285 >        }
1286 >
1287 >        /*
1288 >         * Absolute versions of relation operations.
1289 >         * Subclasses map to these using like-named "sub"
1290 >         * versions that invert senses for descending maps
1291 >         */
1292 >
1293 >        final TreeMap.Entry<K,V> absLowest() {
1294 >            TreeMap.Entry<K,V> e =
1295 >                (fromStart ?  m.getFirstEntry() :
1296 >                 (loInclusive ? m.getCeilingEntry(lo) :
1297 >                                m.getHigherEntry(lo)));
1298 >            return (e == null || tooHigh(e.key)) ? null : e;
1299 >        }
1300 >
1301 >        final TreeMap.Entry<K,V> absHighest() {
1302 >            TreeMap.Entry<K,V> e =
1303 >                (toEnd ?  m.getLastEntry() :
1304 >                 (hiInclusive ?  m.getFloorEntry(hi) :
1305 >                                 m.getLowerEntry(hi)));
1306 >            return (e == null || tooLow(e.key)) ? null : e;
1307 >        }
1308 >
1309 >        final TreeMap.Entry<K,V> absCeiling(K key) {
1310 >            if (tooLow(key))
1311 >                return absLowest();
1312 >            TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
1313 >            return (e == null || tooHigh(e.key)) ? null : e;
1314 >        }
1315 >
1316 >        final TreeMap.Entry<K,V> absHigher(K key) {
1317 >            if (tooLow(key))
1318 >                return absLowest();
1319 >            TreeMap.Entry<K,V> e = m.getHigherEntry(key);
1320 >            return (e == null || tooHigh(e.key)) ? null : e;
1321 >        }
1322 >
1323 >        final TreeMap.Entry<K,V> absFloor(K key) {
1324 >            if (tooHigh(key))
1325 >                return absHighest();
1326 >            TreeMap.Entry<K,V> e = m.getFloorEntry(key);
1327 >            return (e == null || tooLow(e.key)) ? null : e;
1328 >        }
1329 >
1330 >        final TreeMap.Entry<K,V> absLower(K key) {
1331 >            if (tooHigh(key))
1332 >                return absHighest();
1333 >            TreeMap.Entry<K,V> e = m.getLowerEntry(key);
1334 >            return (e == null || tooLow(e.key)) ? null : e;
1335 >        }
1336 >
1337 >        /** Returns the absolute high fence for ascending traversal */
1338 >        final TreeMap.Entry<K,V> absHighFence() {
1339 >            return (toEnd ? null : (hiInclusive ?
1340 >                                    m.getHigherEntry(hi) :
1341 >                                    m.getCeilingEntry(hi)));
1342          }
1343  
1344 +        /** Return the absolute low fence for descending traversal  */
1345 +        final TreeMap.Entry<K,V> absLowFence() {
1346 +            return (fromStart ? null : (loInclusive ?
1347 +                                        m.getLowerEntry(lo) :
1348 +                                        m.getFloorEntry(lo)));
1349 +        }
1350 +
1351 +        // Abstract methods defined in ascending vs descending classes
1352 +        // These relay to the appropriate absolute versions
1353 +
1354 +        abstract TreeMap.Entry<K,V> subLowest();
1355 +        abstract TreeMap.Entry<K,V> subHighest();
1356 +        abstract TreeMap.Entry<K,V> subCeiling(K key);
1357 +        abstract TreeMap.Entry<K,V> subHigher(K key);
1358 +        abstract TreeMap.Entry<K,V> subFloor(K key);
1359 +        abstract TreeMap.Entry<K,V> subLower(K key);
1360 +
1361 +        /** Returns ascending iterator from the perspective of this submap */
1362 +        abstract Iterator<K> keyIterator();
1363 +
1364 +        /** Returns descending iterator from the perspective of this submap */
1365 +        abstract Iterator<K> descendingKeyIterator();
1366 +
1367 +        // public methods
1368 +
1369          public boolean isEmpty() {
1370 <            return entrySet().isEmpty();
1370 >            return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1371          }
1372  
1373 <        public boolean containsKey(Object key) {
1374 <            return inRange(key) && TreeMap.this.containsKey(key);
1373 >        public int size() {
1374 >            return (fromStart && toEnd) ? m.size() : entrySet().size();
1375          }
1376  
1377 <        public V get(Object key) {
1378 <            if (!inRange(key))
1105 <                return null;
1106 <            return TreeMap.this.get(key);
1377 >        public final boolean containsKey(Object key) {
1378 >            return inRange(key) && m.containsKey(key);
1379          }
1380  
1381 <        public V put(K key, V value) {
1381 >        public final V put(K key, V value) {
1382              if (!inRange(key))
1383                  throw new IllegalArgumentException("key out of range");
1384 <            return TreeMap.this.put(key, value);
1384 >            return m.put(key, value);
1385          }
1386  
1387 <        public V remove(Object key) {
1388 <            if (!inRange(key))
1117 <                return null;
1118 <            return TreeMap.this.remove(key);
1387 >        public final V get(Object key) {
1388 >            return !inRange(key)? null :  m.get(key);
1389          }
1390  
1391 <        public Comparator<? super K> comparator() {
1392 <            return comparator;
1391 >        public final V remove(Object key) {
1392 >            return !inRange(key)? null  : m.remove(key);
1393          }
1394  
1395 <        public K firstKey() {
1396 <            TreeMap.Entry<K,V> e = fromStart ? getFirstEntry() : getCeilingEntry(fromKey);
1127 <            K first = key(e);
1128 <            if (!toEnd && compare(first, toKey) >= 0)
1129 <                throw new NoSuchElementException();
1130 <            return first;
1395 >        public final Map.Entry<K,V> ceilingEntry(K key) {
1396 >            return exportEntry(subCeiling(key));
1397          }
1398  
1399 <        public K lastKey() {
1400 <            TreeMap.Entry<K,V> e = toEnd ? getLastEntry() : getLowerEntry(toKey);
1135 <            K last = key(e);
1136 <            if (!fromStart && compare(last, fromKey) < 0)
1137 <                throw new NoSuchElementException();
1138 <            return last;
1399 >        public final K ceilingKey(K key) {
1400 >            return keyOrNull(subCeiling(key));
1401          }
1402  
1403 <        public Map.Entry<K,V> firstEntry() {
1404 <            TreeMap.Entry<K,V> e = fromStart ?
1143 <                getFirstEntry() : getCeilingEntry(fromKey);
1144 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1145 <                return null;
1146 <            return e;
1403 >        public final Map.Entry<K,V> higherEntry(K key) {
1404 >            return exportEntry(subHigher(key));
1405          }
1406  
1407 <        public Map.Entry<K,V> lastEntry() {
1408 <            TreeMap.Entry<K,V> e = toEnd ?
1151 <                getLastEntry() : getLowerEntry(toKey);
1152 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1153 <                return null;
1154 <            return e;
1407 >        public final K higherKey(K key) {
1408 >            return keyOrNull(subHigher(key));
1409          }
1410  
1411 <        public Map.Entry<K,V> pollFirstEntry() {
1412 <            TreeMap.Entry<K,V> e = fromStart ?
1159 <                getFirstEntry() : getCeilingEntry(fromKey);
1160 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1161 <                return null;
1162 <            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1163 <            deleteEntry(e);
1164 <            return result;
1411 >        public final Map.Entry<K,V> floorEntry(K key) {
1412 >            return exportEntry(subFloor(key));
1413          }
1414  
1415 <        public Map.Entry<K,V> pollLastEntry() {
1416 <            TreeMap.Entry<K,V> e = toEnd ?
1169 <                getLastEntry() : getLowerEntry(toKey);
1170 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1171 <                return null;
1172 <            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1173 <            deleteEntry(e);
1174 <            return result;
1415 >        public final K floorKey(K key) {
1416 >            return keyOrNull(subFloor(key));
1417          }
1418  
1419 <        private TreeMap.Entry<K,V> subceiling(K key) {
1420 <            TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1179 <                getCeilingEntry(fromKey) : getCeilingEntry(key);
1180 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1181 <                return null;
1182 <            return e;
1419 >        public final Map.Entry<K,V> lowerEntry(K key) {
1420 >            return exportEntry(subLower(key));
1421          }
1422  
1423 <        public Map.Entry<K,V> ceilingEntry(K key) {
1424 <            TreeMap.Entry<K,V> e = subceiling(key);
1187 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1423 >        public final K lowerKey(K key) {
1424 >            return keyOrNull(subLower(key));
1425          }
1426  
1427 <        public K ceilingKey(K key) {
1428 <            TreeMap.Entry<K,V> e = subceiling(key);
1192 <            return e == null? null : e.key;
1427 >        public final K firstKey() {
1428 >            return key(subLowest());
1429          }
1430  
1431 <
1432 <        private TreeMap.Entry<K,V> subhigher(K key) {
1197 <            TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1198 <                getCeilingEntry(fromKey) : getHigherEntry(key);
1199 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1200 <                return null;
1201 <            return e;
1431 >        public final K lastKey() {
1432 >            return key(subHighest());
1433          }
1434  
1435 <        public Map.Entry<K,V> higherEntry(K key) {
1436 <            TreeMap.Entry<K,V> e = subhigher(key);
1206 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1435 >        public final Map.Entry<K,V> firstEntry() {
1436 >            return exportEntry(subLowest());
1437          }
1438  
1439 <        public K higherKey(K key) {
1440 <            TreeMap.Entry<K,V> e = subhigher(key);
1211 <            return e == null? null : e.key;
1439 >        public final Map.Entry<K,V> lastEntry() {
1440 >            return exportEntry(subHighest());
1441          }
1442  
1443 <        private TreeMap.Entry<K,V> subfloor(K key) {
1444 <            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1445 <                getLowerEntry(toKey) : getFloorEntry(key);
1446 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1447 <                return null;
1448 <            return e;
1443 >        public final Map.Entry<K,V> pollFirstEntry() {
1444 >            TreeMap.Entry<K,V> e = subLowest();
1445 >            Map.Entry<K,V> result = exportEntry(e);
1446 >            if (e != null)
1447 >                m.deleteEntry(e);
1448 >            return result;
1449          }
1450  
1451 <        public Map.Entry<K,V> floorEntry(K key) {
1452 <            TreeMap.Entry<K,V> e = subfloor(key);
1453 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1451 >        public final Map.Entry<K,V> pollLastEntry() {
1452 >            TreeMap.Entry<K,V> e = subHighest();
1453 >            Map.Entry<K,V> result = exportEntry(e);
1454 >            if (e != null)
1455 >                m.deleteEntry(e);
1456 >            return result;
1457          }
1458  
1459 <        public K floorKey(K key) {
1460 <            TreeMap.Entry<K,V> e = subfloor(key);
1461 <            return e == null? null : e.key;
1459 >        // Views
1460 >        transient NavigableMap<K,V> descendingMapView = null;
1461 >        transient EntrySetView entrySetView = null;
1462 >        transient KeySet<K> navigableKeySetView = null;
1463 >
1464 >        public final NavigableSet<K> navigableKeySet() {
1465 >            KeySet<K> nksv = navigableKeySetView;
1466 >            return (nksv != null) ? nksv :
1467 >                (navigableKeySetView = new TreeMap.KeySet(this));
1468          }
1469  
1470 <        private TreeMap.Entry<K,V> sublower(K key) {
1471 <            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1234 <                getLowerEntry(toKey) :  getLowerEntry(key);
1235 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1236 <                return null;
1237 <            return e;
1470 >        public final Set<K> keySet() {
1471 >            return navigableKeySet();
1472          }
1473  
1474 <        public Map.Entry<K,V> lowerEntry(K key) {
1475 <            TreeMap.Entry<K,V> e = sublower(key);
1242 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1474 >        public NavigableSet<K> descendingKeySet() {
1475 >            return descendingMap().navigableKeySet();
1476          }
1477  
1478 <        public K lowerKey(K key) {
1479 <            TreeMap.Entry<K,V> e = sublower(key);
1247 <            return e == null? null : e.key;
1478 >        public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1479 >            return subMap(fromKey, true, toKey, false);
1480          }
1481  
1482 <        private transient Set<Map.Entry<K,V>> entrySet = null;
1482 >        public final SortedMap<K,V> headMap(K toKey) {
1483 >            return headMap(toKey, false);
1484 >        }
1485  
1486 <        public Set<Map.Entry<K,V>> entrySet() {
1487 <            Set<Map.Entry<K,V>> es = entrySet;
1254 <            return (es != null)? es : (entrySet = new EntrySetView());
1486 >        public final SortedMap<K,V> tailMap(K fromKey) {
1487 >            return tailMap(fromKey, true);
1488          }
1489  
1490 <        private class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1490 >        // View classes
1491 >
1492 >        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1493              private transient int size = -1, sizeModCount;
1494  
1495              public int size() {
1496 <                if (size == -1 || sizeModCount != TreeMap.this.modCount) {
1497 <                    size = 0;  sizeModCount = TreeMap.this.modCount;
1496 >                if (fromStart && toEnd)
1497 >                    return m.size();
1498 >                if (size == -1 || sizeModCount != m.modCount) {
1499 >                    sizeModCount = m.modCount;
1500 >                    size = 0;
1501                      Iterator i = iterator();
1502                      while (i.hasNext()) {
1503                          size++;
# Line 1270 | Line 1508 | public class TreeMap<K,V>
1508              }
1509  
1510              public boolean isEmpty() {
1511 <                return !iterator().hasNext();
1511 >                TreeMap.Entry<K,V> n = absLowest();
1512 >                return n == null || tooHigh(n.key);
1513              }
1514  
1515              public boolean contains(Object o) {
# Line 1280 | Line 1519 | public class TreeMap<K,V>
1519                  K key = entry.getKey();
1520                  if (!inRange(key))
1521                      return false;
1522 <                TreeMap.Entry node = getEntry(key);
1522 >                TreeMap.Entry node = m.getEntry(key);
1523                  return node != null &&
1524 <                       valEquals(node.getValue(), entry.getValue());
1524 >                    valEquals(node.getValue(), entry.getValue());
1525              }
1526  
1527              public boolean remove(Object o) {
# Line 1292 | Line 1531 | public class TreeMap<K,V>
1531                  K key = entry.getKey();
1532                  if (!inRange(key))
1533                      return false;
1534 <                TreeMap.Entry<K,V> node = getEntry(key);
1534 >                TreeMap.Entry<K,V> node = m.getEntry(key);
1535                  if (node!=null && valEquals(node.getValue(),entry.getValue())){
1536 <                    deleteEntry(node);
1536 >                    m.deleteEntry(node);
1537                      return true;
1538                  }
1539                  return false;
1540              }
1302
1303            public Iterator<Map.Entry<K,V>> iterator() {
1304                return new SubMapEntryIterator(
1305                    (fromStart ? getFirstEntry() : getCeilingEntry(fromKey)),
1306                    (toEnd     ? null            : getCeilingEntry(toKey)));
1307            }
1308        }
1309
1310        private transient Set<Map.Entry<K,V>> descendingEntrySetView = null;
1311        private transient Set<K> descendingKeySetView = null;
1312
1313        public Set<Map.Entry<K,V>> descendingEntrySet() {
1314            Set<Map.Entry<K,V>> es = descendingEntrySetView;
1315            return (es != null) ? es :
1316                (descendingEntrySetView = new DescendingEntrySetView());
1541          }
1542  
1543 <        public Set<K> descendingKeySet() {
1544 <            Set<K> ks = descendingKeySetView;
1545 <            return (ks != null) ? ks :
1546 <                (descendingKeySetView = new DescendingKeySetView());
1547 <        }
1543 >        /**
1544 >         * Iterators for SubMaps
1545 >         */
1546 >        abstract class SubMapIterator<T> implements Iterator<T> {
1547 >            TreeMap.Entry<K,V> lastReturned;
1548 >            TreeMap.Entry<K,V> next;
1549 >            final K fenceKey;
1550 >            int expectedModCount;
1551  
1552 <        private class DescendingEntrySetView extends EntrySetView {
1553 <            public Iterator<Map.Entry<K,V>> iterator() {
1554 <                return new DescendingSubMapEntryIterator
1555 <                    ((toEnd     ? getLastEntry()  : getLowerEntry(toKey)),
1556 <                     (fromStart ? null            : getLowerEntry(fromKey)));
1552 >            SubMapIterator(TreeMap.Entry<K,V> first,
1553 >                           TreeMap.Entry<K,V> fence) {
1554 >                expectedModCount = m.modCount;
1555 >                lastReturned = null;
1556 >                next = first;
1557 >                fenceKey = fence == null ? null : fence.key;
1558              }
1331        }
1332
1333        private class DescendingKeySetView extends AbstractSet<K> {
1334            public Iterator<K> iterator() {
1335                return new Iterator<K>() {
1336                    private Iterator<Entry<K,V>> i = descendingEntrySet().iterator();
1559  
1560 <                    public boolean hasNext() { return i.hasNext(); }
1561 <                    public K next() { return i.next().getKey(); }
1340 <                    public void remove() { i.remove(); }
1341 <                };
1560 >            public final boolean hasNext() {
1561 >                return next != null && next.key != fenceKey;
1562              }
1563  
1564 <            public int size() {
1565 <                return SubMap.this.size();
1564 >            final TreeMap.Entry<K,V> nextEntry() {
1565 >                TreeMap.Entry<K,V> e = lastReturned = next;
1566 >                if (e == null || e.key == fenceKey)
1567 >                    throw new NoSuchElementException();
1568 >                if (m.modCount != expectedModCount)
1569 >                    throw new ConcurrentModificationException();
1570 >                next = successor(e);
1571 >                return e;
1572              }
1573  
1574 <            public boolean contains(Object k) {
1575 <                return SubMap.this.containsKey(k);
1574 >            final TreeMap.Entry<K,V> prevEntry() {
1575 >                TreeMap.Entry<K,V> e = lastReturned = next;
1576 >                if (e == null || e.key == fenceKey)
1577 >                    throw new NoSuchElementException();
1578 >                if (m.modCount != expectedModCount)
1579 >                    throw new ConcurrentModificationException();
1580 >                next = predecessor(e);
1581 >                return e;
1582              }
1351        }
1583  
1584 <        public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1585 <            if (!inRange2(fromKey))
1586 <                throw new IllegalArgumentException("fromKey out of range");
1587 <            if (!inRange2(toKey))
1588 <                throw new IllegalArgumentException("toKey out of range");
1589 <            return new SubMap(fromKey, toKey);
1590 <        }
1591 <
1592 <        public NavigableMap<K,V> navigableHeadMap(K toKey) {
1593 <            if (!inRange2(toKey))
1594 <                throw new IllegalArgumentException("toKey out of range");
1364 <            return new SubMap(fromStart, fromKey, false, toKey);
1365 <        }
1366 <
1367 <        public NavigableMap<K,V> navigableTailMap(K fromKey) {
1368 <            if (!inRange2(fromKey))
1369 <                throw new IllegalArgumentException("fromKey out of range");
1370 <            return new SubMap(false, fromKey, toEnd, toKey);
1584 >            public void remove() {
1585 >                if (lastReturned == null)
1586 >                    throw new IllegalStateException();
1587 >                if (m.modCount != expectedModCount)
1588 >                    throw new ConcurrentModificationException();
1589 >                if (lastReturned.left != null && lastReturned.right != null)
1590 >                    next = lastReturned;
1591 >                m.deleteEntry(lastReturned);
1592 >                expectedModCount++;
1593 >                lastReturned = null;
1594 >            }
1595          }
1596  
1597 <        public SortedMap<K,V> subMap(K fromKey, K toKey) {
1598 <            return navigableSubMap(fromKey, toKey);
1597 >        final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1598 >            SubMapEntryIterator(TreeMap.Entry<K,V> first,
1599 >                                TreeMap.Entry<K,V> fence) {
1600 >                super(first, fence);
1601 >            }
1602 >            public Map.Entry<K,V> next() {
1603 >                return nextEntry();
1604 >            }
1605          }
1606  
1607 <        public SortedMap<K,V> headMap(K toKey) {
1608 <            return navigableHeadMap(toKey);
1607 >        final class SubMapKeyIterator extends SubMapIterator<K> {
1608 >            SubMapKeyIterator(TreeMap.Entry<K,V> first,
1609 >                              TreeMap.Entry<K,V> fence) {
1610 >                super(first, fence);
1611 >            }
1612 >            public K next() {
1613 >                return nextEntry().key;
1614 >            }
1615          }
1616  
1617 <        public SortedMap<K,V> tailMap(K fromKey) {
1618 <            return navigableTailMap(fromKey);
1619 <        }
1617 >        final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1618 >            DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
1619 >                                          TreeMap.Entry<K,V> fence) {
1620 >                super(last, fence);
1621 >            }
1622  
1623 <        private boolean inRange(Object key) {
1624 <            return (fromStart || compare(key, fromKey) >= 0) &&
1625 <                   (toEnd     || compare(key, toKey)   <  0);
1623 >            public Map.Entry<K,V> next() {
1624 >                return prevEntry();
1625 >            }
1626          }
1627  
1628 <        // This form allows the high endpoint (as well as all legit keys)
1629 <        private boolean inRange2(Object key) {
1630 <            return (fromStart || compare(key, fromKey) >= 0) &&
1631 <                   (toEnd     || compare(key, toKey)   <= 0);
1628 >        final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
1629 >            DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
1630 >                                        TreeMap.Entry<K,V> fence) {
1631 >                super(last, fence);
1632 >            }
1633 >            public K next() {
1634 >                return prevEntry().key;
1635 >            }
1636          }
1637      }
1638  
1639      /**
1640 <     * TreeMap Iterator.
1640 >     * @serial include
1641       */
1642 <    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1643 <        int expectedModCount = TreeMap.this.modCount;
1402 <        Entry<K,V> lastReturned = null;
1403 <        Entry<K,V> next;
1642 >    static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1643 >        private static final long serialVersionUID = 912986545866124060L;
1644  
1645 <        PrivateEntryIterator(Entry<K,V> first) {
1646 <            next = first;
1645 >        AscendingSubMap(TreeMap<K,V> m,
1646 >                        boolean fromStart, K lo, boolean loInclusive,
1647 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1648 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1649          }
1650  
1651 <        public boolean hasNext() {
1652 <            return next != null;
1651 >        public Comparator<? super K> comparator() {
1652 >            return m.comparator();
1653          }
1654  
1655 <        Entry<K,V> nextEntry() {
1656 <            if (next == null)
1657 <                throw new NoSuchElementException();
1658 <            if (modCount != expectedModCount)
1659 <                throw new ConcurrentModificationException();
1660 <            lastReturned = next;
1661 <            next = successor(next);
1662 <            return lastReturned;
1655 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1656 >                                        K toKey,   boolean toInclusive) {
1657 >            if (!inRange(fromKey, fromInclusive))
1658 >                throw new IllegalArgumentException("fromKey out of range");
1659 >            if (!inRange(toKey, toInclusive))
1660 >                throw new IllegalArgumentException("toKey out of range");
1661 >            return new AscendingSubMap(m,
1662 >                                       false, fromKey, fromInclusive,
1663 >                                       false, toKey,   toInclusive);
1664          }
1665  
1666 <        public void remove() {
1667 <            if (lastReturned == null)
1668 <                throw new IllegalStateException();
1669 <            if (modCount != expectedModCount)
1670 <                throw new ConcurrentModificationException();
1671 <            if (lastReturned.left != null && lastReturned.right != null)
1429 <                next = lastReturned;
1430 <            deleteEntry(lastReturned);
1431 <            expectedModCount++;
1432 <            lastReturned = null;
1666 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1667 >            if (!inClosedRange(toKey))
1668 >                throw new IllegalArgumentException("toKey out of range");
1669 >            return new AscendingSubMap(m,
1670 >                                       fromStart, lo,    loInclusive,
1671 >                                       false,     toKey, inclusive);
1672          }
1434    }
1673  
1674 <    class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1675 <        EntryIterator(Entry<K,V> first) {
1676 <            super(first);
1677 <        }
1678 <        public Map.Entry<K,V> next() {
1679 <            return nextEntry();
1674 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1675 >            if (!inRange(fromKey, inclusive))
1676 >                throw new IllegalArgumentException("fromKey out of range");
1677 >            return new AscendingSubMap(m,
1678 >                                       false, fromKey, inclusive,
1679 >                                       toEnd, hi,      hiInclusive);
1680          }
1443    }
1681  
1682 <    class KeyIterator extends PrivateEntryIterator<K> {
1683 <        KeyIterator(Entry<K,V> first) {
1684 <            super(first);
1685 <        }
1686 <        public K next() {
1687 <            return nextEntry().key;
1682 >        public NavigableMap<K,V> descendingMap() {
1683 >            NavigableMap<K,V> mv = descendingMapView;
1684 >            return (mv != null) ? mv :
1685 >                (descendingMapView =
1686 >                 new DescendingSubMap(m,
1687 >                                      fromStart, lo, loInclusive,
1688 >                                      toEnd,     hi, hiInclusive));
1689          }
1452    }
1690  
1691 <    class ValueIterator extends PrivateEntryIterator<V> {
1692 <        ValueIterator(Entry<K,V> first) {
1456 <            super(first);
1691 >        Iterator<K> keyIterator() {
1692 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1693          }
1458        public V next() {
1459            return nextEntry().value;
1460        }
1461    }
1462
1463    class SubMapEntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1464        private final K firstExcludedKey;
1694  
1695 <        SubMapEntryIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1696 <            super(first);
1468 <            firstExcludedKey = (firstExcluded == null
1469 <                                ? null
1470 <                                : firstExcluded.key);
1695 >        Iterator<K> descendingKeyIterator() {
1696 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1697          }
1698  
1699 <        public boolean hasNext() {
1700 <            return next != null && next.key != firstExcludedKey;
1699 >        final class AscendingEntrySetView extends EntrySetView {
1700 >            public Iterator<Map.Entry<K,V>> iterator() {
1701 >                return new SubMapEntryIterator(absLowest(), absHighFence());
1702 >            }
1703          }
1704  
1705 <        public Map.Entry<K,V> next() {
1706 <            if (next == null || next.key == firstExcludedKey)
1707 <                throw new NoSuchElementException();
1480 <            return nextEntry();
1705 >        public Set<Map.Entry<K,V>> entrySet() {
1706 >            EntrySetView es = entrySetView;
1707 >            return (es != null) ? es : new AscendingEntrySetView();
1708          }
1709 +
1710 +        TreeMap.Entry<K,V> subLowest()       { return absLowest(); }
1711 +        TreeMap.Entry<K,V> subHighest()      { return absHighest(); }
1712 +        TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); }
1713 +        TreeMap.Entry<K,V> subHigher(K key)  { return absHigher(key); }
1714 +        TreeMap.Entry<K,V> subFloor(K key)   { return absFloor(key); }
1715 +        TreeMap.Entry<K,V> subLower(K key)   { return absLower(key); }
1716      }
1717  
1718      /**
1719 <     * Base for Descending Iterators.
1719 >     * @serial include
1720       */
1721 <    abstract class DescendingPrivateEntryIterator<T> extends PrivateEntryIterator<T> {
1722 <        DescendingPrivateEntryIterator(Entry<K,V> first) {
1723 <            super(first);
1721 >    static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
1722 >        private static final long serialVersionUID = 912986545866120460L;
1723 >        DescendingSubMap(TreeMap<K,V> m,
1724 >                        boolean fromStart, K lo, boolean loInclusive,
1725 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1726 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1727          }
1728  
1729 <        Entry<K,V> nextEntry() {
1730 <            if (next == null)
1494 <                throw new NoSuchElementException();
1495 <            if (modCount != expectedModCount)
1496 <                throw new ConcurrentModificationException();
1497 <            lastReturned = next;
1498 <            next = predecessor(next);
1499 <            return lastReturned;
1500 <        }
1501 <    }
1729 >        private final Comparator<? super K> reverseComparator =
1730 >            Collections.reverseOrder(m.comparator);
1731  
1732 <    class DescendingEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1733 <        DescendingEntryIterator(Entry<K,V> first) {
1505 <            super(first);
1732 >        public Comparator<? super K> comparator() {
1733 >            return reverseComparator;
1734          }
1735 <        public Map.Entry<K,V> next() {
1736 <            return nextEntry();
1735 >
1736 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1737 >                                        K toKey,   boolean toInclusive) {
1738 >            if (!inRange(fromKey, fromInclusive))
1739 >                throw new IllegalArgumentException("fromKey out of range");
1740 >            if (!inRange(toKey, toInclusive))
1741 >                throw new IllegalArgumentException("toKey out of range");
1742 >            return new DescendingSubMap(m,
1743 >                                        false, toKey,   toInclusive,
1744 >                                        false, fromKey, fromInclusive);
1745          }
1510    }
1746  
1747 <    class DescendingKeyIterator extends DescendingPrivateEntryIterator<K> {
1748 <        DescendingKeyIterator(Entry<K,V> first) {
1749 <            super(first);
1747 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1748 >            if (!inRange(toKey, inclusive))
1749 >                throw new IllegalArgumentException("toKey out of range");
1750 >            return new DescendingSubMap(m,
1751 >                                        false, toKey, inclusive,
1752 >                                        toEnd, hi,    hiInclusive);
1753          }
1754 <        public K next() {
1755 <            return nextEntry().key;
1754 >
1755 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1756 >            if (!inRange(fromKey, inclusive))
1757 >                throw new IllegalArgumentException("fromKey out of range");
1758 >            return new DescendingSubMap(m,
1759 >                                        fromStart, lo, loInclusive,
1760 >                                        false, fromKey, inclusive);
1761          }
1519    }
1762  
1763 +        public NavigableMap<K,V> descendingMap() {
1764 +            NavigableMap<K,V> mv = descendingMapView;
1765 +            return (mv != null) ? mv :
1766 +                (descendingMapView =
1767 +                 new AscendingSubMap(m,
1768 +                                     fromStart, lo, loInclusive,
1769 +                                     toEnd,     hi, hiInclusive));
1770 +        }
1771  
1772 <    class DescendingSubMapEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1773 <        private final K lastExcludedKey;
1772 >        Iterator<K> keyIterator() {
1773 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1774 >        }
1775  
1776 <        DescendingSubMapEntryIterator(Entry<K,V> last, Entry<K,V> lastExcluded) {
1777 <            super(last);
1527 <            lastExcludedKey = (lastExcluded == null
1528 <                                ? null
1529 <                                : lastExcluded.key);
1776 >        Iterator<K> descendingKeyIterator() {
1777 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1778          }
1779  
1780 <        public boolean hasNext() {
1781 <            return next != null && next.key != lastExcludedKey;
1780 >        final class DescendingEntrySetView extends EntrySetView {
1781 >            public Iterator<Map.Entry<K,V>> iterator() {
1782 >                return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
1783 >            }
1784          }
1785  
1786 <        public Map.Entry<K,V> next() {
1787 <            if (next == null || next.key == lastExcludedKey)
1788 <                throw new NoSuchElementException();
1539 <            return nextEntry();
1786 >        public Set<Map.Entry<K,V>> entrySet() {
1787 >            EntrySetView es = entrySetView;
1788 >            return (es != null) ? es : new DescendingEntrySetView();
1789          }
1790  
1791 +        TreeMap.Entry<K,V> subLowest()       { return absHighest(); }
1792 +        TreeMap.Entry<K,V> subHighest()      { return absLowest(); }
1793 +        TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
1794 +        TreeMap.Entry<K,V> subHigher(K key)  { return absLower(key); }
1795 +        TreeMap.Entry<K,V> subFloor(K key)   { return absCeiling(key); }
1796 +        TreeMap.Entry<K,V> subLower(K key)   { return absHigher(key); }
1797      }
1798  
1799      /**
1800 <     * Compares two keys using the correct comparison method for this TreeMap.
1800 >     * This class exists solely for the sake of serialization
1801 >     * compatibility with previous releases of TreeMap that did not
1802 >     * support NavigableMap.  It translates an old-version SubMap into
1803 >     * a new-version AscendingSubMap. This class is never otherwise
1804 >     * used.
1805 >     *
1806 >     * @serial include
1807       */
1808 <    private int compare(Object k1, Object k2) {
1809 <        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1810 <                                : comparator.compare((K)k1, (K)k2);
1808 >    private class SubMap extends AbstractMap<K,V>
1809 >        implements SortedMap<K,V>, java.io.Serializable {
1810 >        private static final long serialVersionUID = -6520786458950516097L;
1811 >        private boolean fromStart = false, toEnd = false;
1812 >        private K fromKey, toKey;
1813 >        private Object readResolve() {
1814 >            return new AscendingSubMap(TreeMap.this,
1815 >                                       fromStart, fromKey, true,
1816 >                                       toEnd, toKey, false);
1817 >        }
1818 >        public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
1819 >        public K lastKey() { throw new InternalError(); }
1820 >        public K firstKey() { throw new InternalError(); }
1821 >        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
1822 >        public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
1823 >        public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
1824 >        public Comparator<? super K> comparator() { throw new InternalError(); }
1825      }
1826  
1827 <    /**
1828 <     * Test two values for equality.  Differs from o1.equals(o2) only in
1554 <     * that it copes with <tt>null</tt> o1 properly.
1555 <     */
1556 <    private static boolean valEquals(Object o1, Object o2) {
1557 <        return (o1==null ? o2==null : o1.equals(o2));
1558 <    }
1827 >
1828 >    // Red-black mechanics
1829  
1830      private static final boolean RED   = false;
1831      private static final boolean BLACK = true;
# Line 1565 | Line 1835 | public class TreeMap<K,V>
1835       * user (see Map.Entry).
1836       */
1837  
1838 <    static class Entry<K,V> implements Map.Entry<K,V> {
1838 >    static final class Entry<K,V> implements Map.Entry<K,V> {
1839          K key;
1840          V value;
1841          Entry<K,V> left = null;
# Line 1617 | Line 1887 | public class TreeMap<K,V>
1887          public boolean equals(Object o) {
1888              if (!(o instanceof Map.Entry))
1889                  return false;
1890 <            Map.Entry e = (Map.Entry)o;
1890 >            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1891  
1892              return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
1893          }
# Line 1637 | Line 1907 | public class TreeMap<K,V>
1907       * Returns the first Entry in the TreeMap (according to the TreeMap's
1908       * key-sort function).  Returns null if the TreeMap is empty.
1909       */
1910 <    private Entry<K,V> getFirstEntry() {
1910 >    final Entry<K,V> getFirstEntry() {
1911          Entry<K,V> p = root;
1912          if (p != null)
1913              while (p.left != null)
# Line 1649 | Line 1919 | public class TreeMap<K,V>
1919       * Returns the last Entry in the TreeMap (according to the TreeMap's
1920       * key-sort function).  Returns null if the TreeMap is empty.
1921       */
1922 <    private Entry<K,V> getLastEntry() {
1922 >    final Entry<K,V> getLastEntry() {
1923          Entry<K,V> p = root;
1924          if (p != null)
1925              while (p.right != null)
# Line 1660 | Line 1930 | public class TreeMap<K,V>
1930      /**
1931       * Returns the successor of the specified Entry, or null if no such.
1932       */
1933 <    private Entry<K,V> successor(Entry<K,V> t) {
1933 >    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
1934          if (t == null)
1935              return null;
1936          else if (t.right != null) {
# Line 1682 | Line 1952 | public class TreeMap<K,V>
1952      /**
1953       * Returns the predecessor of the specified Entry, or null if no such.
1954       */
1955 <    private Entry<K,V> predecessor(Entry<K,V> t) {
1955 >    static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {
1956          if (t == null)
1957              return null;
1958          else if (t.left != null) {
# Line 1732 | Line 2002 | public class TreeMap<K,V>
2002          return (p == null) ? null: p.right;
2003      }
2004  
2005 <    /** From CLR **/
2005 >    /** From CLR */
2006      private void rotateLeft(Entry<K,V> p) {
2007 <        Entry<K,V> r = p.right;
2008 <        p.right = r.left;
2009 <        if (r.left != null)
2010 <            r.left.parent = p;
2011 <        r.parent = p.parent;
2012 <        if (p.parent == null)
2013 <            root = r;
2014 <        else if (p.parent.left == p)
2015 <            p.parent.left = r;
2016 <        else
2017 <            p.parent.right = r;
2018 <        r.left = p;
2019 <        p.parent = r;
2007 >        if (p != null) {
2008 >            Entry<K,V> r = p.right;
2009 >            p.right = r.left;
2010 >            if (r.left != null)
2011 >                r.left.parent = p;
2012 >            r.parent = p.parent;
2013 >            if (p.parent == null)
2014 >                root = r;
2015 >            else if (p.parent.left == p)
2016 >                p.parent.left = r;
2017 >            else
2018 >                p.parent.right = r;
2019 >            r.left = p;
2020 >            p.parent = r;
2021 >        }
2022      }
2023  
2024 <    /** From CLR **/
2024 >    /** From CLR */
2025      private void rotateRight(Entry<K,V> p) {
2026 <        Entry<K,V> l = p.left;
2027 <        p.left = l.right;
2028 <        if (l.right != null) l.right.parent = p;
2029 <        l.parent = p.parent;
2030 <        if (p.parent == null)
2031 <            root = l;
2032 <        else if (p.parent.right == p)
2033 <            p.parent.right = l;
2034 <        else p.parent.left = l;
2035 <        l.right = p;
2036 <        p.parent = l;
2026 >        if (p != null) {
2027 >            Entry<K,V> l = p.left;
2028 >            p.left = l.right;
2029 >            if (l.right != null) l.right.parent = p;
2030 >            l.parent = p.parent;
2031 >            if (p.parent == null)
2032 >                root = l;
2033 >            else if (p.parent.right == p)
2034 >                p.parent.right = l;
2035 >            else p.parent.left = l;
2036 >            l.right = p;
2037 >            p.parent = l;
2038 >        }
2039      }
2040  
2041 <
1768 <    /** From CLR **/
2041 >    /** From CLR */
2042      private void fixAfterInsertion(Entry<K,V> x) {
2043          x.color = RED;
2044  
# Line 1784 | Line 2057 | public class TreeMap<K,V>
2057                      }
2058                      setColor(parentOf(x), BLACK);
2059                      setColor(parentOf(parentOf(x)), RED);
2060 <                    if (parentOf(parentOf(x)) != null)
1788 <                        rotateRight(parentOf(parentOf(x)));
2060 >                    rotateRight(parentOf(parentOf(x)));
2061                  }
2062              } else {
2063                  Entry<K,V> y = leftOf(parentOf(parentOf(x)));
# Line 1799 | Line 2071 | public class TreeMap<K,V>
2071                          x = parentOf(x);
2072                          rotateRight(x);
2073                      }
2074 <                    setColor(parentOf(x),  BLACK);
2074 >                    setColor(parentOf(x), BLACK);
2075                      setColor(parentOf(parentOf(x)), RED);
2076 <                    if (parentOf(parentOf(x)) != null)
1805 <                        rotateLeft(parentOf(parentOf(x)));
2076 >                    rotateLeft(parentOf(parentOf(x)));
2077                  }
2078              }
2079          }
# Line 1812 | Line 2083 | public class TreeMap<K,V>
2083      /**
2084       * Delete node p, and then rebalance the tree.
2085       */
1815
2086      private void deleteEntry(Entry<K,V> p) {
2087 <        decrementSize();
2087 >        modCount++;
2088 >        size--;
2089  
2090          // If strictly internal, copy successor's element to p and then make p
2091          // point to successor.
# Line 1860 | Line 2131 | public class TreeMap<K,V>
2131          }
2132      }
2133  
2134 <    /** From CLR **/
2134 >    /** From CLR */
2135      private void fixAfterDeletion(Entry<K,V> x) {
2136          while (x != root && colorOf(x) == BLACK) {
2137              if (x == leftOf(parentOf(x))) {
# Line 1875 | Line 2146 | public class TreeMap<K,V>
2146  
2147                  if (colorOf(leftOf(sib))  == BLACK &&
2148                      colorOf(rightOf(sib)) == BLACK) {
2149 <                    setColor(sib,  RED);
2149 >                    setColor(sib, RED);
2150                      x = parentOf(x);
2151                  } else {
2152                      if (colorOf(rightOf(sib)) == BLACK) {
# Line 1902 | Line 2173 | public class TreeMap<K,V>
2173  
2174                  if (colorOf(rightOf(sib)) == BLACK &&
2175                      colorOf(leftOf(sib)) == BLACK) {
2176 <                    setColor(sib,  RED);
2176 >                    setColor(sib, RED);
2177                      x = parentOf(x);
2178                  } else {
2179                      if (colorOf(leftOf(sib)) == BLACK) {
# Line 1953 | Line 2224 | public class TreeMap<K,V>
2224          }
2225      }
2226  
1956
1957
2227      /**
2228       * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e.,
2229       * deserialize it).
# Line 1970 | Line 2239 | public class TreeMap<K,V>
2239          buildFromSorted(size, null, s, null);
2240      }
2241  
2242 <    /** Intended to be called only from TreeSet.readObject **/
2242 >    /** Intended to be called only from TreeSet.readObject */
2243      void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2244          throws java.io.IOException, ClassNotFoundException {
2245          buildFromSorted(size, null, s, defaultVal);
2246      }
2247  
2248 <    /** Intended to be called only from TreeSet.addAll **/
2248 >    /** Intended to be called only from TreeSet.addAll */
2249      void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2250          try {
2251              buildFromSorted(set.size(), set.iterator(), null, defaultVal);
# Line 2016 | Line 2285 | public class TreeMap<K,V>
2285       * @throws ClassNotFoundException propagated from readObject.
2286       *         This cannot occur if str is null.
2287       */
2288 <    private
2289 <    void buildFromSorted(int size, Iterator it,
2290 <                         java.io.ObjectInputStream str,
2022 <                         V defaultVal)
2288 >    private void buildFromSorted(int size, Iterator it,
2289 >                                 java.io.ObjectInputStream str,
2290 >                                 V defaultVal)
2291          throws  java.io.IOException, ClassNotFoundException {
2292          this.size = size;
2293 <        root =
2294 <            buildFromSorted(0, 0, size-1, computeRedLevel(size),
2027 <                            it, str, defaultVal);
2293 >        root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
2294 >                               it, str, defaultVal);
2295      }
2296  
2297      /**
2298       * Recursive "helper method" that does the real work of the
2299 <     * of the previous method.  Identically named parameters have
2299 >     * previous method.  Identically named parameters have
2300       * identical definitions.  Additional parameters are documented below.
2301       * It is assumed that the comparator and size fields of the TreeMap are
2302       * already set prior to calling this method.  (It ignores both fields.)

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines