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.25 by jsr166, Mon Dec 5 02:56:59 2005 UTC vs.
Revision 1.42 by jsr166, Tue Jan 30 03:54:29 2007 UTC

# Line 1 | Line 1
1   /*
2   * %W% %E%
3   *
4 < * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
4 > * Copyright 2007 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      /**
# Line 336 | 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 360 | 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 382 | 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)
388 <            return null;
389 <
390 <        while (true) {
371 >        while (p != null) {
372              int cmp = compare(key, p.key);
373              if (cmp < 0) {
374                  if (p.left != null)
# Line 409 | Line 390 | public class TreeMap<K,V>
390              } else
391                  return p;
392          }
393 +        return null;
394      }
395  
396      /**
# Line 416 | 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)
422 <            return null;
423 <
424 <        while (true) {
403 >        while (p != null) {
404              int cmp = compare(key, p.key);
405              if (cmp > 0) {
406                  if (p.right != null)
# Line 444 | Line 423 | public class TreeMap<K,V>
423                  return p;
424  
425          }
426 +        return null;
427      }
428  
429      /**
# Line 452 | 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)
458 <            return null;
459 <
460 <        while (true) {
437 >        while (p != null) {
438              int cmp = compare(key, p.key);
439              if (cmp < 0) {
440                  if (p.left != null)
# Line 478 | Line 455 | public class TreeMap<K,V>
455                  }
456              }
457          }
458 +        return null;
459      }
460  
461      /**
# Line 485 | 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)
491 <            return null;
492 <
493 <        while (true) {
468 >        while (p != null) {
469              int cmp = compare(key, p.key);
470              if (cmp > 0) {
471                  if (p.right != null)
# Line 511 | Line 486 | public class TreeMap<K,V>
486                  }
487              }
488          }
489 <    }
515 <
516 <    /**
517 <     * Returns the key corresponding to the specified Entry.
518 <     * @throws NoSuchElementException if the Entry is null
519 <     */
520 <    private static <K> K key(Entry<K,?> e) {
521 <        if (e==null)
522 <            throw new NoSuchElementException();
523 <        return e.key;
489 >        return null;
490      }
491  
492      /**
# Line 543 | Line 509 | public class TreeMap<K,V>
509       */
510      public V put(K key, V value) {
511          Entry<K,V> t = root;
546
512          if (t == null) {
513 <            // TBD
514 < //             if (key == null) {
515 < //                 if (comparator == null)
516 < //                     throw new NullPointerException();
517 < //                 comparator.compare(key, key);
553 < //             }
554 <            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 {
567 <                    incrementSize();
568 <                    t.left = new Entry<K,V>(key, value, t);
569 <                    fixAfterInsertion(t.left);
570 <                    return null;
571 <                }
572 <            } else { // cmp > 0
573 <                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);
538 <                    fixAfterInsertion(t.right);
539 <                    return null;
540 <                }
541 <            }
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 635 | 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 654 | 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();
658 <        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();
666 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
644 >        return exportEntry(getLastEntry());
645      }
646  
647      /**
# Line 671 | 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);
677 <        deleteEntry(p);
652 >        Map.Entry<K,V> result = exportEntry(p);
653 >        if (p != null)
654 >            deleteEntry(p);
655          return result;
656      }
657  
# Line 683 | 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);
689 <        deleteEntry(p);
663 >        Map.Entry<K,V> result = exportEntry(p);
664 >        if (p != null)
665 >            deleteEntry(p);
666          return result;
667      }
668  
# Line 698 | 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);
702 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
677 >        return exportEntry(getLowerEntry(key));
678      }
679  
680      /**
# Line 710 | 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);
714 <        return (e == null)? null : e.key;
688 >        return keyOrNull(getLowerEntry(key));
689      }
690  
691      /**
# Line 722 | 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);
726 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
699 >        return exportEntry(getFloorEntry(key));
700      }
701  
702      /**
# Line 734 | 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);
738 <        return (e == null)? null : e.key;
710 >        return keyOrNull(getFloorEntry(key));
711      }
712  
713      /**
# Line 746 | 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);
750 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
721 >        return exportEntry(getCeilingEntry(key));
722      }
723  
724      /**
# Line 758 | 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);
762 <        return (e == null)? null : e.key;
732 >        return keyOrNull(getCeilingEntry(key));
733      }
734  
735      /**
# Line 770 | 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);
774 <        return (e == null)? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
743 >        return exportEntry(getHigherEntry(key));
744      }
745  
746      /**
# Line 782 | 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);
786 <        return (e == null)? null : e.key;
754 >        return keyOrNull(getHigherEntry(key));
755      }
756  
757      // Views
# Line 793 | 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 812 | Line 780 | public class TreeMap<K,V>
780       * operations.
781       */
782      public Set<K> keySet() {
783 <        Set<K> ks = keySet;
816 <        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();
826 <        }
827 <
828 <        public boolean contains(Object o) {
829 <            return containsKey(o);
830 <        }
831 <
832 <        public boolean remove(Object o) {
833 <            int oldSize = size;
834 <            TreeMap.this.remove(o);
835 <            return size != oldSize;
836 <        }
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 860 | 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 870 | 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))
874 <                if (valEquals(e.getValue(), o))
875 <                    return true;
876 <            return false;
940 >            return TreeMap.this.containsValue(o);
941          }
942  
943          public boolean remove(Object o) {
# Line 891 | Line 955 | public class TreeMap<K,V>
955          }
956      }
957  
894    /**
895     * Returns a {@link Set} view of the mappings contained in this map.
896     * The set's iterator returns the entries in ascending key order.
897     * The set is backed by the map, so changes to the map are
898     * reflected in the set, and vice-versa.  If the map is modified
899     * while an iteration over the set is in progress (except through
900     * the iterator's own <tt>remove</tt> operation, or through the
901     * <tt>setValue</tt> operation on a map entry returned by the
902     * iterator) the results of the iteration are undefined.  The set
903     * supports element removal, which removes the corresponding
904     * mapping from the map, via the <tt>Iterator.remove</tt>,
905     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
906     * <tt>clear</tt> operations.  It does not support the
907     * <tt>add</tt> or <tt>addAll</tt> operations.
908     */
909    public Set<Map.Entry<K,V>> entrySet() {
910        Set<Map.Entry<K,V>> es = entrySet;
911        return (es != null) ? es : (entrySet = new EntrySet());
912    }
913
958      class EntrySet extends AbstractSet<Map.Entry<K,V>> {
959          public Iterator<Map.Entry<K,V>> iterator() {
960              return new EntryIterator(getFirstEntry());
# Line 947 | 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 >            // deleted entries are replaced by their successors
1121 >            if (lastReturned.left != null && lastReturned.right != null)
1122 >                next = lastReturned;
1123 >            deleteEntry(lastReturned);
1124 >            expectedModCount = modCount;
1125 >            lastReturned = null;
1126 >        }
1127 >    }
1128 >
1129 >    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1130 >        EntryIterator(Entry<K,V> first) {
1131 >            super(first);
1132 >        }
1133 >        public Map.Entry<K,V> next() {
1134 >            return nextEntry();
1135 >        }
1136 >    }
1137 >
1138 >    final class ValueIterator extends PrivateEntryIterator<V> {
1139 >        ValueIterator(Entry<K,V> first) {
1140 >            super(first);
1141 >        }
1142 >        public V next() {
1143 >            return nextEntry().value;
1144 >        }
1145 >    }
1146 >
1147 >    final class KeyIterator extends PrivateEntryIterator<K> {
1148 >        KeyIterator(Entry<K,V> first) {
1149 >            super(first);
1150 >        }
1151 >        public K next() {
1152 >            return nextEntry().key;
1153 >        }
1154      }
1155  
1156 <    class DescendingKeySet extends KeySet {
1157 <        public Iterator<K> iterator() {
1158 <            return new DescendingKeyIterator(getLastEntry());
1156 >    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
1157 >        DescendingKeyIterator(Entry<K,V> first) {
1158 >            super(first);
1159 >        }
1160 >        public K next() {
1161 >            return prevEntry().key;
1162          }
1163      }
1164  
1165 +    // Little utilities
1166 +
1167      /**
1168 <     * @throws ClassCastException       {@inheritDoc}
980 <     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
981 <     *         null and this map uses natural ordering, or its comparator
982 <     *         does not permit null keys
983 <     * @throws IllegalArgumentException {@inheritDoc}
984 <     * @since 1.6
1168 >     * Compares two keys using the correct comparison method for this TreeMap.
1169       */
1170 <    public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1171 <        return new SubMap(fromKey, toKey);
1170 >    final int compare(Object k1, Object k2) {
1171 >        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1172 >            : comparator.compare((K)k1, (K)k2);
1173      }
1174  
1175      /**
1176 <     * @throws ClassCastException       {@inheritDoc}
1177 <     * @throws NullPointerException if <tt>toKey</tt> is null
993 <     *         and this map uses natural ordering, or its comparator
994 <     *         does not permit null keys
995 <     * @throws IllegalArgumentException {@inheritDoc}
996 <     * @since 1.6
1176 >     * Test two values for equality.  Differs from o1.equals(o2) only in
1177 >     * that it copes with <tt>null</tt> o1 properly.
1178       */
1179 <    public NavigableMap<K,V> navigableHeadMap(K toKey) {
1180 <        return new SubMap(toKey, true);
1179 >    final static boolean valEquals(Object o1, Object o2) {
1180 >        return (o1==null ? o2==null : o1.equals(o2));
1181      }
1182  
1183      /**
1184 <     * @throws ClassCastException       {@inheritDoc}
1004 <     * @throws NullPointerException if <tt>fromKey</tt> is null
1005 <     *         and this map uses natural ordering, or its comparator
1006 <     *         does not permit null keys
1007 <     * @throws IllegalArgumentException {@inheritDoc}
1008 <     * @since 1.6
1184 >     * Return SimpleImmutableEntry for entry, or null if null
1185       */
1186 <    public NavigableMap<K,V> navigableTailMap(K fromKey) {
1187 <        return new SubMap(fromKey, false);
1186 >    static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
1187 >        return e == null? null :
1188 >            new AbstractMap.SimpleImmutableEntry<K,V>(e);
1189      }
1190  
1191      /**
1192 <     * Equivalent to {@link #navigableSubMap} but with a return type
1016 <     * conforming to the <tt>SortedMap</tt> interface.
1017 <     *
1018 <     * <p>{@inheritDoc}
1019 <     *
1020 <     * @throws ClassCastException       {@inheritDoc}
1021 <     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
1022 <     *         null and this map uses natural ordering, or its comparator
1023 <     *         does not permit null keys
1024 <     * @throws IllegalArgumentException {@inheritDoc}
1192 >     * Return key for entry, or null if null
1193       */
1194 <    public SortedMap<K,V> subMap(K fromKey, K toKey) {
1195 <        return new SubMap(fromKey, toKey);
1194 >    static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
1195 >        return e == null? null : e.key;
1196      }
1197  
1198      /**
1199 <     * Equivalent to {@link #navigableHeadMap} but with a return type
1200 <     * conforming to the <tt>SortedMap</tt> interface.
1033 <     *
1034 <     * <p>{@inheritDoc}
1035 <     *
1036 <     * @throws ClassCastException       {@inheritDoc}
1037 <     * @throws NullPointerException if <tt>toKey</tt> is null
1038 <     *         and this map uses natural ordering, or its comparator
1039 <     *         does not permit null keys
1040 <     * @throws IllegalArgumentException {@inheritDoc}
1199 >     * Returns the key corresponding to the specified Entry.
1200 >     * @throws NoSuchElementException if the Entry is null
1201       */
1202 <    public SortedMap<K,V> headMap(K toKey) {
1203 <        return new SubMap(toKey, true);
1202 >    static <K> K key(Entry<K,?> e) {
1203 >        if (e==null)
1204 >            throw new NoSuchElementException();
1205 >        return e.key;
1206      }
1207  
1208 +
1209 +    // SubMaps
1210 +
1211      /**
1212 <     * Equivalent to {@link #navigableTailMap} but with a return type
1213 <     * conforming to the <tt>SortedMap</tt> interface.
1049 <     *
1050 <     * <p>{@inheritDoc}
1051 <     *
1052 <     * @throws ClassCastException       {@inheritDoc}
1053 <     * @throws NullPointerException if <tt>fromKey</tt> is null
1054 <     *         and this map uses natural ordering, or its comparator
1055 <     *         does not permit null keys
1056 <     * @throws IllegalArgumentException {@inheritDoc}
1212 >     * Dummy value serving as unmatchable fence key for unbounded
1213 >     * SubMapIterators
1214       */
1215 <    public SortedMap<K,V> tailMap(K fromKey) {
1059 <        return new SubMap(fromKey, false);
1060 <    }
1215 >    private static final Object UNBOUNDED = new Object();
1216  
1217 <    private class SubMap
1218 <        extends AbstractMap<K,V>
1219 <        implements NavigableMap<K,V>, java.io.Serializable {
1220 <        private static final long serialVersionUID = -6520786458950516097L;
1217 >    /**
1218 >     * @serial include
1219 >     */
1220 >    static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
1221 >        implements NavigableMap<K,V>, java.io.Serializable {
1222 >        /**
1223 >         * The backing map.
1224 >         */
1225 >        final TreeMap<K,V> m;
1226  
1227          /**
1228 <         * fromKey is significant only if fromStart is false.  Similarly,
1229 <         * toKey is significant only if toStart is false.
1228 >         * Endpoints are represented as triples (fromStart, lo,
1229 >         * loInclusive) and (toEnd, hi, hiInclusive). If fromStart is
1230 >         * true, then the low (absolute) bound is the start of the
1231 >         * backing map, and the other values are ignored. Otherwise,
1232 >         * if loInclusive is true, lo is the inclusive bound, else lo
1233 >         * is the exclusive bound. Similarly for the upper bound.
1234           */
1235 <        private boolean fromStart = false, toEnd = false;
1236 <        private K fromKey, toKey;
1235 >        final K lo, hi;
1236 >        final boolean fromStart, toEnd;
1237 >        final boolean loInclusive, hiInclusive;
1238 >
1239 >        NavigableSubMap(TreeMap<K,V> m,
1240 >                        boolean fromStart, K lo, boolean loInclusive,
1241 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1242 >            if (!fromStart && !toEnd) {
1243 >                if (m.compare(lo, hi) > 0)
1244 >                    throw new IllegalArgumentException("fromKey > toKey");
1245 >            } else {
1246 >                if (!fromStart) // type check
1247 >                    m.compare(lo, lo);
1248 >                if (!toEnd)
1249 >                    m.compare(hi, hi);
1250 >            }
1251  
1252 <        SubMap(K fromKey, K toKey) {
1253 <            if (compare(fromKey, toKey) > 0)
1254 <                throw new IllegalArgumentException("fromKey > toKey");
1255 <            this.fromKey = fromKey;
1256 <            this.toKey = toKey;
1252 >            this.m = m;
1253 >            this.fromStart = fromStart;
1254 >            this.lo = lo;
1255 >            this.loInclusive = loInclusive;
1256 >            this.toEnd = toEnd;
1257 >            this.hi = hi;
1258 >            this.hiInclusive = hiInclusive;
1259          }
1260  
1261 <        SubMap(K key, boolean headMap) {
1262 <            compare(key, key); // Type-check key
1263 <
1264 <            if (headMap) {
1265 <                fromStart = true;
1266 <                toKey = key;
1267 <            } else {
1088 <                toEnd = true;
1089 <                fromKey = key;
1261 >        // internal utilities
1262 >
1263 >        final boolean tooLow(Object key) {
1264 >            if (!fromStart) {
1265 >                int c = m.compare(key, lo);
1266 >                if (c < 0 || (c == 0 && !loInclusive))
1267 >                    return true;
1268              }
1269 +            return false;
1270          }
1271  
1272 <        SubMap(boolean fromStart, K fromKey, boolean toEnd, K toKey) {
1273 <            this.fromStart = fromStart;
1274 <            this.fromKey= fromKey;
1275 <            this.toEnd = toEnd;
1276 <            this.toKey = toKey;
1272 >        final boolean tooHigh(Object key) {
1273 >            if (!toEnd) {
1274 >                int c = m.compare(key, hi);
1275 >                if (c > 0 || (c == 0 && !hiInclusive))
1276 >                    return true;
1277 >            }
1278 >            return false;
1279 >        }
1280 >
1281 >        final boolean inRange(Object key) {
1282 >            return !tooLow(key) && !tooHigh(key);
1283          }
1284  
1285 +        final boolean inClosedRange(Object key) {
1286 +            return (fromStart || m.compare(key, lo) >= 0)
1287 +                && (toEnd || m.compare(hi, key) >= 0);
1288 +        }
1289 +
1290 +        final boolean inRange(Object key, boolean inclusive) {
1291 +            return inclusive ? inRange(key) : inClosedRange(key);
1292 +        }
1293 +
1294 +        /*
1295 +         * Absolute versions of relation operations.
1296 +         * Subclasses map to these using like-named "sub"
1297 +         * versions that invert senses for descending maps
1298 +         */
1299 +
1300 +        final TreeMap.Entry<K,V> absLowest() {
1301 +            TreeMap.Entry<K,V> e =
1302 +                (fromStart ?  m.getFirstEntry() :
1303 +                 (loInclusive ? m.getCeilingEntry(lo) :
1304 +                                m.getHigherEntry(lo)));
1305 +            return (e == null || tooHigh(e.key)) ? null : e;
1306 +        }
1307 +
1308 +        final TreeMap.Entry<K,V> absHighest() {
1309 +            TreeMap.Entry<K,V> e =
1310 +                (toEnd ?  m.getLastEntry() :
1311 +                 (hiInclusive ?  m.getFloorEntry(hi) :
1312 +                                 m.getLowerEntry(hi)));
1313 +            return (e == null || tooLow(e.key)) ? null : e;
1314 +        }
1315 +
1316 +        final TreeMap.Entry<K,V> absCeiling(K key) {
1317 +            if (tooLow(key))
1318 +                return absLowest();
1319 +            TreeMap.Entry<K,V> e = m.getCeilingEntry(key);
1320 +            return (e == null || tooHigh(e.key)) ? null : e;
1321 +        }
1322 +
1323 +        final TreeMap.Entry<K,V> absHigher(K key) {
1324 +            if (tooLow(key))
1325 +                return absLowest();
1326 +            TreeMap.Entry<K,V> e = m.getHigherEntry(key);
1327 +            return (e == null || tooHigh(e.key)) ? null : e;
1328 +        }
1329 +
1330 +        final TreeMap.Entry<K,V> absFloor(K key) {
1331 +            if (tooHigh(key))
1332 +                return absHighest();
1333 +            TreeMap.Entry<K,V> e = m.getFloorEntry(key);
1334 +            return (e == null || tooLow(e.key)) ? null : e;
1335 +        }
1336 +
1337 +        final TreeMap.Entry<K,V> absLower(K key) {
1338 +            if (tooHigh(key))
1339 +                return absHighest();
1340 +            TreeMap.Entry<K,V> e = m.getLowerEntry(key);
1341 +            return (e == null || tooLow(e.key)) ? null : e;
1342 +        }
1343 +
1344 +        /** Returns the absolute high fence for ascending traversal */
1345 +        final TreeMap.Entry<K,V> absHighFence() {
1346 +            return (toEnd ? null : (hiInclusive ?
1347 +                                    m.getHigherEntry(hi) :
1348 +                                    m.getCeilingEntry(hi)));
1349 +        }
1350 +
1351 +        /** Return the absolute low fence for descending traversal  */
1352 +        final TreeMap.Entry<K,V> absLowFence() {
1353 +            return (fromStart ? null : (loInclusive ?
1354 +                                        m.getLowerEntry(lo) :
1355 +                                        m.getFloorEntry(lo)));
1356 +        }
1357 +
1358 +        // Abstract methods defined in ascending vs descending classes
1359 +        // These relay to the appropriate absolute versions
1360 +
1361 +        abstract TreeMap.Entry<K,V> subLowest();
1362 +        abstract TreeMap.Entry<K,V> subHighest();
1363 +        abstract TreeMap.Entry<K,V> subCeiling(K key);
1364 +        abstract TreeMap.Entry<K,V> subHigher(K key);
1365 +        abstract TreeMap.Entry<K,V> subFloor(K key);
1366 +        abstract TreeMap.Entry<K,V> subLower(K key);
1367 +
1368 +        /** Returns ascending iterator from the perspective of this submap */
1369 +        abstract Iterator<K> keyIterator();
1370 +
1371 +        /** Returns descending iterator from the perspective of this submap */
1372 +        abstract Iterator<K> descendingKeyIterator();
1373 +
1374 +        // public methods
1375 +
1376          public boolean isEmpty() {
1377 <            return entrySet().isEmpty();
1377 >            return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty();
1378          }
1379  
1380 <        public boolean containsKey(Object key) {
1381 <            return inRange(key) && TreeMap.this.containsKey(key);
1380 >        public int size() {
1381 >            return (fromStart && toEnd) ? m.size() : entrySet().size();
1382          }
1383  
1384 <        public V get(Object key) {
1385 <            if (!inRange(key))
1110 <                return null;
1111 <            return TreeMap.this.get(key);
1384 >        public final boolean containsKey(Object key) {
1385 >            return inRange(key) && m.containsKey(key);
1386          }
1387  
1388 <        public V put(K key, V value) {
1388 >        public final V put(K key, V value) {
1389              if (!inRange(key))
1390                  throw new IllegalArgumentException("key out of range");
1391 <            return TreeMap.this.put(key, value);
1391 >            return m.put(key, value);
1392          }
1393  
1394 <        public V remove(Object key) {
1395 <            if (!inRange(key))
1122 <                return null;
1123 <            return TreeMap.this.remove(key);
1394 >        public final V get(Object key) {
1395 >            return !inRange(key)? null :  m.get(key);
1396          }
1397  
1398 <        public Comparator<? super K> comparator() {
1399 <            return comparator;
1398 >        public final V remove(Object key) {
1399 >            return !inRange(key)? null  : m.remove(key);
1400          }
1401  
1402 <        public K firstKey() {
1403 <            TreeMap.Entry<K,V> e = fromStart ? getFirstEntry() : getCeilingEntry(fromKey);
1132 <            K first = key(e);
1133 <            if (!toEnd && compare(first, toKey) >= 0)
1134 <                throw new NoSuchElementException();
1135 <            return first;
1402 >        public final Map.Entry<K,V> ceilingEntry(K key) {
1403 >            return exportEntry(subCeiling(key));
1404          }
1405  
1406 <        public K lastKey() {
1407 <            TreeMap.Entry<K,V> e = toEnd ? getLastEntry() : getLowerEntry(toKey);
1140 <            K last = key(e);
1141 <            if (!fromStart && compare(last, fromKey) < 0)
1142 <                throw new NoSuchElementException();
1143 <            return last;
1406 >        public final K ceilingKey(K key) {
1407 >            return keyOrNull(subCeiling(key));
1408          }
1409  
1410 <        public Map.Entry<K,V> firstEntry() {
1411 <            TreeMap.Entry<K,V> e = fromStart ?
1148 <                getFirstEntry() : getCeilingEntry(fromKey);
1149 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1150 <                return null;
1151 <            return e;
1410 >        public final Map.Entry<K,V> higherEntry(K key) {
1411 >            return exportEntry(subHigher(key));
1412          }
1413  
1414 <        public Map.Entry<K,V> lastEntry() {
1415 <            TreeMap.Entry<K,V> e = toEnd ?
1156 <                getLastEntry() : getLowerEntry(toKey);
1157 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1158 <                return null;
1159 <            return e;
1414 >        public final K higherKey(K key) {
1415 >            return keyOrNull(subHigher(key));
1416          }
1417  
1418 <        public Map.Entry<K,V> pollFirstEntry() {
1419 <            TreeMap.Entry<K,V> e = fromStart ?
1164 <                getFirstEntry() : getCeilingEntry(fromKey);
1165 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1166 <                return null;
1167 <            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1168 <            deleteEntry(e);
1169 <            return result;
1418 >        public final Map.Entry<K,V> floorEntry(K key) {
1419 >            return exportEntry(subFloor(key));
1420          }
1421  
1422 <        public Map.Entry<K,V> pollLastEntry() {
1423 <            TreeMap.Entry<K,V> e = toEnd ?
1174 <                getLastEntry() : getLowerEntry(toKey);
1175 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1176 <                return null;
1177 <            Map.Entry<K,V> result = new AbstractMap.SimpleImmutableEntry<K,V>(e);
1178 <            deleteEntry(e);
1179 <            return result;
1422 >        public final K floorKey(K key) {
1423 >            return keyOrNull(subFloor(key));
1424          }
1425  
1426 <        private TreeMap.Entry<K,V> subceiling(K key) {
1427 <            TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1184 <                getCeilingEntry(fromKey) : getCeilingEntry(key);
1185 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1186 <                return null;
1187 <            return e;
1426 >        public final Map.Entry<K,V> lowerEntry(K key) {
1427 >            return exportEntry(subLower(key));
1428          }
1429  
1430 <        public Map.Entry<K,V> ceilingEntry(K key) {
1431 <            TreeMap.Entry<K,V> e = subceiling(key);
1192 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1430 >        public final K lowerKey(K key) {
1431 >            return keyOrNull(subLower(key));
1432          }
1433  
1434 <        public K ceilingKey(K key) {
1435 <            TreeMap.Entry<K,V> e = subceiling(key);
1197 <            return e == null? null : e.key;
1434 >        public final K firstKey() {
1435 >            return key(subLowest());
1436          }
1437  
1438 <
1439 <        private TreeMap.Entry<K,V> subhigher(K key) {
1202 <            TreeMap.Entry<K,V> e = (!fromStart && compare(key, fromKey) < 0)?
1203 <                getCeilingEntry(fromKey) : getHigherEntry(key);
1204 <            if (e == null || (!toEnd && compare(e.key, toKey) >= 0))
1205 <                return null;
1206 <            return e;
1438 >        public final K lastKey() {
1439 >            return key(subHighest());
1440          }
1441  
1442 <        public Map.Entry<K,V> higherEntry(K key) {
1443 <            TreeMap.Entry<K,V> e = subhigher(key);
1211 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1442 >        public final Map.Entry<K,V> firstEntry() {
1443 >            return exportEntry(subLowest());
1444          }
1445  
1446 <        public K higherKey(K key) {
1447 <            TreeMap.Entry<K,V> e = subhigher(key);
1216 <            return e == null? null : e.key;
1446 >        public final Map.Entry<K,V> lastEntry() {
1447 >            return exportEntry(subHighest());
1448          }
1449  
1450 <        private TreeMap.Entry<K,V> subfloor(K key) {
1451 <            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1452 <                getLowerEntry(toKey) : getFloorEntry(key);
1453 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1454 <                return null;
1455 <            return e;
1450 >        public final Map.Entry<K,V> pollFirstEntry() {
1451 >            TreeMap.Entry<K,V> e = subLowest();
1452 >            Map.Entry<K,V> result = exportEntry(e);
1453 >            if (e != null)
1454 >                m.deleteEntry(e);
1455 >            return result;
1456          }
1457  
1458 <        public Map.Entry<K,V> floorEntry(K key) {
1459 <            TreeMap.Entry<K,V> e = subfloor(key);
1460 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1458 >        public final Map.Entry<K,V> pollLastEntry() {
1459 >            TreeMap.Entry<K,V> e = subHighest();
1460 >            Map.Entry<K,V> result = exportEntry(e);
1461 >            if (e != null)
1462 >                m.deleteEntry(e);
1463 >            return result;
1464          }
1465  
1466 <        public K floorKey(K key) {
1467 <            TreeMap.Entry<K,V> e = subfloor(key);
1468 <            return e == null? null : e.key;
1466 >        // Views
1467 >        transient NavigableMap<K,V> descendingMapView = null;
1468 >        transient EntrySetView entrySetView = null;
1469 >        transient KeySet<K> navigableKeySetView = null;
1470 >
1471 >        public final NavigableSet<K> navigableKeySet() {
1472 >            KeySet<K> nksv = navigableKeySetView;
1473 >            return (nksv != null) ? nksv :
1474 >                (navigableKeySetView = new TreeMap.KeySet(this));
1475          }
1476  
1477 <        private TreeMap.Entry<K,V> sublower(K key) {
1478 <            TreeMap.Entry<K,V> e = (!toEnd && compare(key, toKey) >= 0)?
1239 <                getLowerEntry(toKey) :  getLowerEntry(key);
1240 <            if (e == null || (!fromStart && compare(e.key, fromKey) < 0))
1241 <                return null;
1242 <            return e;
1477 >        public final Set<K> keySet() {
1478 >            return navigableKeySet();
1479          }
1480  
1481 <        public Map.Entry<K,V> lowerEntry(K key) {
1482 <            TreeMap.Entry<K,V> e = sublower(key);
1247 <            return e == null? null : new AbstractMap.SimpleImmutableEntry<K,V>(e);
1481 >        public NavigableSet<K> descendingKeySet() {
1482 >            return descendingMap().navigableKeySet();
1483          }
1484  
1485 <        public K lowerKey(K key) {
1486 <            TreeMap.Entry<K,V> e = sublower(key);
1252 <            return e == null? null : e.key;
1485 >        public final SortedMap<K,V> subMap(K fromKey, K toKey) {
1486 >            return subMap(fromKey, true, toKey, false);
1487          }
1488  
1489 <        private transient Set<Map.Entry<K,V>> entrySet = null;
1489 >        public final SortedMap<K,V> headMap(K toKey) {
1490 >            return headMap(toKey, false);
1491 >        }
1492  
1493 <        public Set<Map.Entry<K,V>> entrySet() {
1494 <            Set<Map.Entry<K,V>> es = entrySet;
1259 <            return (es != null)? es : (entrySet = new EntrySetView());
1493 >        public final SortedMap<K,V> tailMap(K fromKey) {
1494 >            return tailMap(fromKey, true);
1495          }
1496  
1497 <        private class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1497 >        // View classes
1498 >
1499 >        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
1500              private transient int size = -1, sizeModCount;
1501  
1502              public int size() {
1503 <                if (size == -1 || sizeModCount != TreeMap.this.modCount) {
1504 <                    size = 0;  sizeModCount = TreeMap.this.modCount;
1503 >                if (fromStart && toEnd)
1504 >                    return m.size();
1505 >                if (size == -1 || sizeModCount != m.modCount) {
1506 >                    sizeModCount = m.modCount;
1507 >                    size = 0;
1508                      Iterator i = iterator();
1509                      while (i.hasNext()) {
1510                          size++;
# Line 1275 | Line 1515 | public class TreeMap<K,V>
1515              }
1516  
1517              public boolean isEmpty() {
1518 <                return !iterator().hasNext();
1518 >                TreeMap.Entry<K,V> n = absLowest();
1519 >                return n == null || tooHigh(n.key);
1520              }
1521  
1522              public boolean contains(Object o) {
# Line 1285 | Line 1526 | public class TreeMap<K,V>
1526                  K key = entry.getKey();
1527                  if (!inRange(key))
1528                      return false;
1529 <                TreeMap.Entry node = getEntry(key);
1529 >                TreeMap.Entry node = m.getEntry(key);
1530                  return node != null &&
1531 <                       valEquals(node.getValue(), entry.getValue());
1531 >                    valEquals(node.getValue(), entry.getValue());
1532              }
1533  
1534              public boolean remove(Object o) {
# Line 1297 | Line 1538 | public class TreeMap<K,V>
1538                  K key = entry.getKey();
1539                  if (!inRange(key))
1540                      return false;
1541 <                TreeMap.Entry<K,V> node = getEntry(key);
1541 >                TreeMap.Entry<K,V> node = m.getEntry(key);
1542                  if (node!=null && valEquals(node.getValue(),entry.getValue())){
1543 <                    deleteEntry(node);
1543 >                    m.deleteEntry(node);
1544                      return true;
1545                  }
1546                  return false;
1547              }
1307
1308            public Iterator<Map.Entry<K,V>> iterator() {
1309                return new SubMapEntryIterator(
1310                    (fromStart ? getFirstEntry() : getCeilingEntry(fromKey)),
1311                    (toEnd     ? null            : getCeilingEntry(toKey)));
1312            }
1548          }
1549  
1550 <        private transient Set<Map.Entry<K,V>> descendingEntrySetView = null;
1551 <        private transient Set<K> descendingKeySetView = null;
1552 <
1553 <        public Set<Map.Entry<K,V>> descendingEntrySet() {
1554 <            Set<Map.Entry<K,V>> es = descendingEntrySetView;
1555 <            return (es != null) ? es :
1556 <                (descendingEntrySetView = new DescendingEntrySetView());
1557 <        }
1323 <
1324 <        public Set<K> descendingKeySet() {
1325 <            Set<K> ks = descendingKeySetView;
1326 <            return (ks != null) ? ks :
1327 <                (descendingKeySetView = new DescendingKeySetView());
1328 <        }
1550 >        /**
1551 >         * Iterators for SubMaps
1552 >         */
1553 >        abstract class SubMapIterator<T> implements Iterator<T> {
1554 >            TreeMap.Entry<K,V> lastReturned;
1555 >            TreeMap.Entry<K,V> next;
1556 >            final Object fenceKey;
1557 >            int expectedModCount;
1558  
1559 <        private class DescendingEntrySetView extends EntrySetView {
1560 <            public Iterator<Map.Entry<K,V>> iterator() {
1561 <                return new DescendingSubMapEntryIterator
1562 <                    ((toEnd     ? getLastEntry()  : getLowerEntry(toKey)),
1563 <                     (fromStart ? null            : getLowerEntry(fromKey)));
1559 >            SubMapIterator(TreeMap.Entry<K,V> first,
1560 >                           TreeMap.Entry<K,V> fence) {
1561 >                expectedModCount = m.modCount;
1562 >                lastReturned = null;
1563 >                next = first;
1564 >                fenceKey = fence == null ? UNBOUNDED : fence.key;
1565              }
1336        }
1566  
1567 <        private class DescendingKeySetView extends AbstractSet<K> {
1568 <            public Iterator<K> iterator() {
1569 <                return new Iterator<K>() {
1341 <                    private Iterator<Entry<K,V>> i = descendingEntrySet().iterator();
1567 >            public final boolean hasNext() {
1568 >                return next != null && next.key != fenceKey;
1569 >            }
1570  
1571 <                    public boolean hasNext() { return i.hasNext(); }
1572 <                    public K next() { return i.next().getKey(); }
1573 <                    public void remove() { i.remove(); }
1574 <                };
1571 >            final TreeMap.Entry<K,V> nextEntry() {
1572 >                TreeMap.Entry<K,V> e = lastReturned = next;
1573 >                if (e == null || e.key == fenceKey)
1574 >                    throw new NoSuchElementException();
1575 >                if (m.modCount != expectedModCount)
1576 >                    throw new ConcurrentModificationException();
1577 >                next = successor(e);
1578 >                return e;
1579              }
1580  
1581 <            public int size() {
1582 <                return SubMap.this.size();
1581 >            final TreeMap.Entry<K,V> prevEntry() {
1582 >                TreeMap.Entry<K,V> e = lastReturned = next;
1583 >                if (e == null || e.key == fenceKey)
1584 >                    throw new NoSuchElementException();
1585 >                if (m.modCount != expectedModCount)
1586 >                    throw new ConcurrentModificationException();
1587 >                next = predecessor(e);
1588 >                return e;
1589              }
1590  
1591 <            public boolean contains(Object k) {
1592 <                return SubMap.this.containsKey(k);
1591 >            final void removeAscending() {
1592 >                if (lastReturned == null)
1593 >                    throw new IllegalStateException();
1594 >                if (m.modCount != expectedModCount)
1595 >                    throw new ConcurrentModificationException();
1596 >                // deleted entries are replaced by their successors
1597 >                if (lastReturned.left != null && lastReturned.right != null)
1598 >                    next = lastReturned;
1599 >                m.deleteEntry(lastReturned);
1600 >                lastReturned = null;
1601 >                expectedModCount = m.modCount;
1602              }
1356        }
1603  
1604 <        public NavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
1605 <            if (!inRange2(fromKey))
1606 <                throw new IllegalArgumentException("fromKey out of range");
1607 <            if (!inRange2(toKey))
1608 <                throw new IllegalArgumentException("toKey out of range");
1609 <            return new SubMap(fromKey, toKey);
1610 <        }
1604 >            final void removeDescending() {
1605 >                if (lastReturned == null)
1606 >                    throw new IllegalStateException();
1607 >                if (m.modCount != expectedModCount)
1608 >                    throw new ConcurrentModificationException();
1609 >                m.deleteEntry(lastReturned);
1610 >                lastReturned = null;
1611 >                expectedModCount = m.modCount;
1612 >            }
1613  
1366        public NavigableMap<K,V> navigableHeadMap(K toKey) {
1367            if (!inRange2(toKey))
1368                throw new IllegalArgumentException("toKey out of range");
1369            return new SubMap(fromStart, fromKey, false, toKey);
1614          }
1615  
1616 <        public NavigableMap<K,V> navigableTailMap(K fromKey) {
1617 <            if (!inRange2(fromKey))
1618 <                throw new IllegalArgumentException("fromKey out of range");
1619 <            return new SubMap(false, fromKey, toEnd, toKey);
1620 <        }
1621 <
1622 <        public SortedMap<K,V> subMap(K fromKey, K toKey) {
1623 <            return navigableSubMap(fromKey, toKey);
1616 >        final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1617 >            SubMapEntryIterator(TreeMap.Entry<K,V> first,
1618 >                                TreeMap.Entry<K,V> fence) {
1619 >                super(first, fence);
1620 >            }
1621 >            public Map.Entry<K,V> next() {
1622 >                return nextEntry();
1623 >            }
1624 >            public void remove() {
1625 >                removeAscending();
1626 >            }
1627          }
1628  
1629 <        public SortedMap<K,V> headMap(K toKey) {
1630 <            return navigableHeadMap(toKey);
1629 >        final class SubMapKeyIterator extends SubMapIterator<K> {
1630 >            SubMapKeyIterator(TreeMap.Entry<K,V> first,
1631 >                              TreeMap.Entry<K,V> fence) {
1632 >                super(first, fence);
1633 >            }
1634 >            public K next() {
1635 >                return nextEntry().key;
1636 >            }
1637 >            public void remove() {
1638 >                removeAscending();
1639 >            }
1640          }
1641  
1642 <        public SortedMap<K,V> tailMap(K fromKey) {
1643 <            return navigableTailMap(fromKey);
1644 <        }
1642 >        final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
1643 >            DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
1644 >                                          TreeMap.Entry<K,V> fence) {
1645 >                super(last, fence);
1646 >            }
1647  
1648 <        private boolean inRange(Object key) {
1649 <            return (fromStart || compare(key, fromKey) >= 0) &&
1650 <                   (toEnd     || compare(key, toKey)   <  0);
1648 >            public Map.Entry<K,V> next() {
1649 >                return prevEntry();
1650 >            }
1651 >            public void remove() {
1652 >                removeDescending();
1653 >            }
1654          }
1655  
1656 <        // This form allows the high endpoint (as well as all legit keys)
1657 <        private boolean inRange2(Object key) {
1658 <            return (fromStart || compare(key, fromKey) >= 0) &&
1659 <                   (toEnd     || compare(key, toKey)   <= 0);
1656 >        final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
1657 >            DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
1658 >                                        TreeMap.Entry<K,V> fence) {
1659 >                super(last, fence);
1660 >            }
1661 >            public K next() {
1662 >                return prevEntry().key;
1663 >            }
1664 >            public void remove() {
1665 >                removeDescending();
1666 >            }
1667          }
1668      }
1669  
1670      /**
1671 <     * TreeMap Iterator.
1671 >     * @serial include
1672       */
1673 <    abstract class PrivateEntryIterator<T> implements Iterator<T> {
1674 <        int expectedModCount = TreeMap.this.modCount;
1407 <        Entry<K,V> lastReturned = null;
1408 <        Entry<K,V> next;
1673 >    static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
1674 >        private static final long serialVersionUID = 912986545866124060L;
1675  
1676 <        PrivateEntryIterator(Entry<K,V> first) {
1677 <            next = first;
1676 >        AscendingSubMap(TreeMap<K,V> m,
1677 >                        boolean fromStart, K lo, boolean loInclusive,
1678 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1679 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1680          }
1681  
1682 <        public boolean hasNext() {
1683 <            return next != null;
1682 >        public Comparator<? super K> comparator() {
1683 >            return m.comparator();
1684          }
1685  
1686 <        Entry<K,V> nextEntry() {
1687 <            if (next == null)
1688 <                throw new NoSuchElementException();
1689 <            if (modCount != expectedModCount)
1690 <                throw new ConcurrentModificationException();
1691 <            lastReturned = next;
1692 <            next = successor(next);
1693 <            return lastReturned;
1686 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1687 >                                        K toKey,   boolean toInclusive) {
1688 >            if (!inRange(fromKey, fromInclusive))
1689 >                throw new IllegalArgumentException("fromKey out of range");
1690 >            if (!inRange(toKey, toInclusive))
1691 >                throw new IllegalArgumentException("toKey out of range");
1692 >            return new AscendingSubMap(m,
1693 >                                       false, fromKey, fromInclusive,
1694 >                                       false, toKey,   toInclusive);
1695          }
1696  
1697 <        public void remove() {
1698 <            if (lastReturned == null)
1699 <                throw new IllegalStateException();
1700 <            if (modCount != expectedModCount)
1701 <                throw new ConcurrentModificationException();
1702 <            if (lastReturned.left != null && lastReturned.right != null)
1434 <                next = lastReturned;
1435 <            deleteEntry(lastReturned);
1436 <            expectedModCount++;
1437 <            lastReturned = null;
1697 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1698 >            if (!inRange(toKey, inclusive))
1699 >                throw new IllegalArgumentException("toKey out of range");
1700 >            return new AscendingSubMap(m,
1701 >                                       fromStart, lo,    loInclusive,
1702 >                                       false,     toKey, inclusive);
1703          }
1439    }
1704  
1705 <    class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1706 <        EntryIterator(Entry<K,V> first) {
1707 <            super(first);
1708 <        }
1709 <        public Map.Entry<K,V> next() {
1710 <            return nextEntry();
1705 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1706 >            if (!inRange(fromKey, inclusive))
1707 >                throw new IllegalArgumentException("fromKey out of range");
1708 >            return new AscendingSubMap(m,
1709 >                                       false, fromKey, inclusive,
1710 >                                       toEnd, hi,      hiInclusive);
1711          }
1448    }
1712  
1713 <    class KeyIterator extends PrivateEntryIterator<K> {
1714 <        KeyIterator(Entry<K,V> first) {
1715 <            super(first);
1716 <        }
1717 <        public K next() {
1718 <            return nextEntry().key;
1713 >        public NavigableMap<K,V> descendingMap() {
1714 >            NavigableMap<K,V> mv = descendingMapView;
1715 >            return (mv != null) ? mv :
1716 >                (descendingMapView =
1717 >                 new DescendingSubMap(m,
1718 >                                      fromStart, lo, loInclusive,
1719 >                                      toEnd,     hi, hiInclusive));
1720          }
1457    }
1721  
1722 <    class ValueIterator extends PrivateEntryIterator<V> {
1723 <        ValueIterator(Entry<K,V> first) {
1461 <            super(first);
1722 >        Iterator<K> keyIterator() {
1723 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1724          }
1463        public V next() {
1464            return nextEntry().value;
1465        }
1466    }
1467
1468    class SubMapEntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
1469        private final K firstExcludedKey;
1725  
1726 <        SubMapEntryIterator(Entry<K,V> first, Entry<K,V> firstExcluded) {
1727 <            super(first);
1473 <            firstExcludedKey = (firstExcluded == null
1474 <                                ? null
1475 <                                : firstExcluded.key);
1726 >        Iterator<K> descendingKeyIterator() {
1727 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1728          }
1729  
1730 <        public boolean hasNext() {
1731 <            return next != null && next.key != firstExcludedKey;
1730 >        final class AscendingEntrySetView extends EntrySetView {
1731 >            public Iterator<Map.Entry<K,V>> iterator() {
1732 >                return new SubMapEntryIterator(absLowest(), absHighFence());
1733 >            }
1734          }
1735  
1736 <        public Map.Entry<K,V> next() {
1737 <            if (next == null || next.key == firstExcludedKey)
1738 <                throw new NoSuchElementException();
1485 <            return nextEntry();
1736 >        public Set<Map.Entry<K,V>> entrySet() {
1737 >            EntrySetView es = entrySetView;
1738 >            return (es != null) ? es : new AscendingEntrySetView();
1739          }
1740 +
1741 +        TreeMap.Entry<K,V> subLowest()       { return absLowest(); }
1742 +        TreeMap.Entry<K,V> subHighest()      { return absHighest(); }
1743 +        TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); }
1744 +        TreeMap.Entry<K,V> subHigher(K key)  { return absHigher(key); }
1745 +        TreeMap.Entry<K,V> subFloor(K key)   { return absFloor(key); }
1746 +        TreeMap.Entry<K,V> subLower(K key)   { return absLower(key); }
1747      }
1748  
1749      /**
1750 <     * Base for Descending Iterators.
1750 >     * @serial include
1751       */
1752 <    abstract class DescendingPrivateEntryIterator<T> extends PrivateEntryIterator<T> {
1753 <        DescendingPrivateEntryIterator(Entry<K,V> first) {
1754 <            super(first);
1752 >    static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
1753 >        private static final long serialVersionUID = 912986545866120460L;
1754 >        DescendingSubMap(TreeMap<K,V> m,
1755 >                        boolean fromStart, K lo, boolean loInclusive,
1756 >                        boolean toEnd,     K hi, boolean hiInclusive) {
1757 >            super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
1758          }
1759  
1760 <        Entry<K,V> nextEntry() {
1761 <            if (next == null)
1499 <                throw new NoSuchElementException();
1500 <            if (modCount != expectedModCount)
1501 <                throw new ConcurrentModificationException();
1502 <            lastReturned = next;
1503 <            next = predecessor(next);
1504 <            return lastReturned;
1505 <        }
1506 <    }
1760 >        private final Comparator<? super K> reverseComparator =
1761 >            Collections.reverseOrder(m.comparator);
1762  
1763 <    class DescendingEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1764 <        DescendingEntryIterator(Entry<K,V> first) {
1510 <            super(first);
1763 >        public Comparator<? super K> comparator() {
1764 >            return reverseComparator;
1765          }
1766 <        public Map.Entry<K,V> next() {
1767 <            return nextEntry();
1766 >
1767 >        public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
1768 >                                        K toKey,   boolean toInclusive) {
1769 >            if (!inRange(fromKey, fromInclusive))
1770 >                throw new IllegalArgumentException("fromKey out of range");
1771 >            if (!inRange(toKey, toInclusive))
1772 >                throw new IllegalArgumentException("toKey out of range");
1773 >            return new DescendingSubMap(m,
1774 >                                        false, toKey,   toInclusive,
1775 >                                        false, fromKey, fromInclusive);
1776          }
1515    }
1777  
1778 <    class DescendingKeyIterator extends DescendingPrivateEntryIterator<K> {
1779 <        DescendingKeyIterator(Entry<K,V> first) {
1780 <            super(first);
1778 >        public NavigableMap<K,V> headMap(K toKey, boolean inclusive) {
1779 >            if (!inRange(toKey, inclusive))
1780 >                throw new IllegalArgumentException("toKey out of range");
1781 >            return new DescendingSubMap(m,
1782 >                                        false, toKey, inclusive,
1783 >                                        toEnd, hi,    hiInclusive);
1784          }
1785 <        public K next() {
1786 <            return nextEntry().key;
1785 >
1786 >        public NavigableMap<K,V> tailMap(K fromKey, boolean inclusive){
1787 >            if (!inRange(fromKey, inclusive))
1788 >                throw new IllegalArgumentException("fromKey out of range");
1789 >            return new DescendingSubMap(m,
1790 >                                        fromStart, lo, loInclusive,
1791 >                                        false, fromKey, inclusive);
1792          }
1524    }
1793  
1794 +        public NavigableMap<K,V> descendingMap() {
1795 +            NavigableMap<K,V> mv = descendingMapView;
1796 +            return (mv != null) ? mv :
1797 +                (descendingMapView =
1798 +                 new AscendingSubMap(m,
1799 +                                     fromStart, lo, loInclusive,
1800 +                                     toEnd,     hi, hiInclusive));
1801 +        }
1802  
1803 <    class DescendingSubMapEntryIterator extends DescendingPrivateEntryIterator<Map.Entry<K,V>> {
1804 <        private final K lastExcludedKey;
1803 >        Iterator<K> keyIterator() {
1804 >            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
1805 >        }
1806  
1807 <        DescendingSubMapEntryIterator(Entry<K,V> last, Entry<K,V> lastExcluded) {
1808 <            super(last);
1532 <            lastExcludedKey = (lastExcluded == null
1533 <                                ? null
1534 <                                : lastExcluded.key);
1807 >        Iterator<K> descendingKeyIterator() {
1808 >            return new SubMapKeyIterator(absLowest(), absHighFence());
1809          }
1810  
1811 <        public boolean hasNext() {
1812 <            return next != null && next.key != lastExcludedKey;
1811 >        final class DescendingEntrySetView extends EntrySetView {
1812 >            public Iterator<Map.Entry<K,V>> iterator() {
1813 >                return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
1814 >            }
1815          }
1816  
1817 <        public Map.Entry<K,V> next() {
1818 <            if (next == null || next.key == lastExcludedKey)
1819 <                throw new NoSuchElementException();
1544 <            return nextEntry();
1817 >        public Set<Map.Entry<K,V>> entrySet() {
1818 >            EntrySetView es = entrySetView;
1819 >            return (es != null) ? es : new DescendingEntrySetView();
1820          }
1821  
1822 +        TreeMap.Entry<K,V> subLowest()       { return absHighest(); }
1823 +        TreeMap.Entry<K,V> subHighest()      { return absLowest(); }
1824 +        TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
1825 +        TreeMap.Entry<K,V> subHigher(K key)  { return absLower(key); }
1826 +        TreeMap.Entry<K,V> subFloor(K key)   { return absCeiling(key); }
1827 +        TreeMap.Entry<K,V> subLower(K key)   { return absHigher(key); }
1828      }
1829  
1830      /**
1831 <     * Compares two keys using the correct comparison method for this TreeMap.
1831 >     * This class exists solely for the sake of serialization
1832 >     * compatibility with previous releases of TreeMap that did not
1833 >     * support NavigableMap.  It translates an old-version SubMap into
1834 >     * a new-version AscendingSubMap. This class is never otherwise
1835 >     * used.
1836 >     *
1837 >     * @serial include
1838       */
1839 <    private int compare(Object k1, Object k2) {
1840 <        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
1841 <                                : comparator.compare((K)k1, (K)k2);
1839 >    private class SubMap extends AbstractMap<K,V>
1840 >        implements SortedMap<K,V>, java.io.Serializable {
1841 >        private static final long serialVersionUID = -6520786458950516097L;
1842 >        private boolean fromStart = false, toEnd = false;
1843 >        private K fromKey, toKey;
1844 >        private Object readResolve() {
1845 >            return new AscendingSubMap(TreeMap.this,
1846 >                                       fromStart, fromKey, true,
1847 >                                       toEnd, toKey, false);
1848 >        }
1849 >        public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
1850 >        public K lastKey() { throw new InternalError(); }
1851 >        public K firstKey() { throw new InternalError(); }
1852 >        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
1853 >        public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
1854 >        public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
1855 >        public Comparator<? super K> comparator() { throw new InternalError(); }
1856      }
1857  
1858 <    /**
1859 <     * Test two values for equality.  Differs from o1.equals(o2) only in
1559 <     * that it copes with <tt>null</tt> o1 properly.
1560 <     */
1561 <    private static boolean valEquals(Object o1, Object o2) {
1562 <        return (o1==null ? o2==null : o1.equals(o2));
1563 <    }
1858 >
1859 >    // Red-black mechanics
1860  
1861      private static final boolean RED   = false;
1862      private static final boolean BLACK = true;
# Line 1570 | Line 1866 | public class TreeMap<K,V>
1866       * user (see Map.Entry).
1867       */
1868  
1869 <    static class Entry<K,V> implements Map.Entry<K,V> {
1869 >    static final class Entry<K,V> implements Map.Entry<K,V> {
1870          K key;
1871          V value;
1872          Entry<K,V> left = null;
# Line 1622 | Line 1918 | public class TreeMap<K,V>
1918          public boolean equals(Object o) {
1919              if (!(o instanceof Map.Entry))
1920                  return false;
1921 <            Map.Entry e = (Map.Entry)o;
1921 >            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
1922  
1923              return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
1924          }
# Line 1642 | Line 1938 | public class TreeMap<K,V>
1938       * Returns the first Entry in the TreeMap (according to the TreeMap's
1939       * key-sort function).  Returns null if the TreeMap is empty.
1940       */
1941 <    private Entry<K,V> getFirstEntry() {
1941 >    final Entry<K,V> getFirstEntry() {
1942          Entry<K,V> p = root;
1943          if (p != null)
1944              while (p.left != null)
# Line 1654 | Line 1950 | public class TreeMap<K,V>
1950       * Returns the last Entry in the TreeMap (according to the TreeMap's
1951       * key-sort function).  Returns null if the TreeMap is empty.
1952       */
1953 <    private Entry<K,V> getLastEntry() {
1953 >    final Entry<K,V> getLastEntry() {
1954          Entry<K,V> p = root;
1955          if (p != null)
1956              while (p.right != null)
# Line 1665 | Line 1961 | public class TreeMap<K,V>
1961      /**
1962       * Returns the successor of the specified Entry, or null if no such.
1963       */
1964 <    private Entry<K,V> successor(Entry<K,V> t) {
1964 >    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
1965          if (t == null)
1966              return null;
1967          else if (t.right != null) {
# Line 1687 | Line 1983 | public class TreeMap<K,V>
1983      /**
1984       * Returns the predecessor of the specified Entry, or null if no such.
1985       */
1986 <    private Entry<K,V> predecessor(Entry<K,V> t) {
1986 >    static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {
1987          if (t == null)
1988              return null;
1989          else if (t.left != null) {
# Line 1737 | Line 2033 | public class TreeMap<K,V>
2033          return (p == null) ? null: p.right;
2034      }
2035  
2036 <    /** From CLR **/
2036 >    /** From CLR */
2037      private void rotateLeft(Entry<K,V> p) {
2038 <        Entry<K,V> r = p.right;
2039 <        p.right = r.left;
2040 <        if (r.left != null)
2041 <            r.left.parent = p;
2042 <        r.parent = p.parent;
2043 <        if (p.parent == null)
2044 <            root = r;
2045 <        else if (p.parent.left == p)
2046 <            p.parent.left = r;
2047 <        else
2048 <            p.parent.right = r;
2049 <        r.left = p;
2050 <        p.parent = r;
2038 >        if (p != null) {
2039 >            Entry<K,V> r = p.right;
2040 >            p.right = r.left;
2041 >            if (r.left != null)
2042 >                r.left.parent = p;
2043 >            r.parent = p.parent;
2044 >            if (p.parent == null)
2045 >                root = r;
2046 >            else if (p.parent.left == p)
2047 >                p.parent.left = r;
2048 >            else
2049 >                p.parent.right = r;
2050 >            r.left = p;
2051 >            p.parent = r;
2052 >        }
2053      }
2054  
2055 <    /** From CLR **/
2055 >    /** From CLR */
2056      private void rotateRight(Entry<K,V> p) {
2057 <        Entry<K,V> l = p.left;
2058 <        p.left = l.right;
2059 <        if (l.right != null) l.right.parent = p;
2060 <        l.parent = p.parent;
2061 <        if (p.parent == null)
2062 <            root = l;
2063 <        else if (p.parent.right == p)
2064 <            p.parent.right = l;
2065 <        else p.parent.left = l;
2066 <        l.right = p;
2067 <        p.parent = l;
2057 >        if (p != null) {
2058 >            Entry<K,V> l = p.left;
2059 >            p.left = l.right;
2060 >            if (l.right != null) l.right.parent = p;
2061 >            l.parent = p.parent;
2062 >            if (p.parent == null)
2063 >                root = l;
2064 >            else if (p.parent.right == p)
2065 >                p.parent.right = l;
2066 >            else p.parent.left = l;
2067 >            l.right = p;
2068 >            p.parent = l;
2069 >        }
2070      }
2071  
2072 <
1773 <    /** From CLR **/
2072 >    /** From CLR */
2073      private void fixAfterInsertion(Entry<K,V> x) {
2074          x.color = RED;
2075  
# Line 1789 | Line 2088 | public class TreeMap<K,V>
2088                      }
2089                      setColor(parentOf(x), BLACK);
2090                      setColor(parentOf(parentOf(x)), RED);
2091 <                    if (parentOf(parentOf(x)) != null)
1793 <                        rotateRight(parentOf(parentOf(x)));
2091 >                    rotateRight(parentOf(parentOf(x)));
2092                  }
2093              } else {
2094                  Entry<K,V> y = leftOf(parentOf(parentOf(x)));
# Line 1804 | Line 2102 | public class TreeMap<K,V>
2102                          x = parentOf(x);
2103                          rotateRight(x);
2104                      }
2105 <                    setColor(parentOf(x),  BLACK);
2105 >                    setColor(parentOf(x), BLACK);
2106                      setColor(parentOf(parentOf(x)), RED);
2107 <                    if (parentOf(parentOf(x)) != null)
1810 <                        rotateLeft(parentOf(parentOf(x)));
2107 >                    rotateLeft(parentOf(parentOf(x)));
2108                  }
2109              }
2110          }
# Line 1817 | Line 2114 | public class TreeMap<K,V>
2114      /**
2115       * Delete node p, and then rebalance the tree.
2116       */
1820
2117      private void deleteEntry(Entry<K,V> p) {
2118 <        decrementSize();
2118 >        modCount++;
2119 >        size--;
2120  
2121          // If strictly internal, copy successor's element to p and then make p
2122          // point to successor.
# Line 1865 | Line 2162 | public class TreeMap<K,V>
2162          }
2163      }
2164  
2165 <    /** From CLR **/
2165 >    /** From CLR */
2166      private void fixAfterDeletion(Entry<K,V> x) {
2167          while (x != root && colorOf(x) == BLACK) {
2168              if (x == leftOf(parentOf(x))) {
# Line 1880 | Line 2177 | public class TreeMap<K,V>
2177  
2178                  if (colorOf(leftOf(sib))  == BLACK &&
2179                      colorOf(rightOf(sib)) == BLACK) {
2180 <                    setColor(sib,  RED);
2180 >                    setColor(sib, RED);
2181                      x = parentOf(x);
2182                  } else {
2183                      if (colorOf(rightOf(sib)) == BLACK) {
# Line 1907 | Line 2204 | public class TreeMap<K,V>
2204  
2205                  if (colorOf(rightOf(sib)) == BLACK &&
2206                      colorOf(leftOf(sib)) == BLACK) {
2207 <                    setColor(sib,  RED);
2207 >                    setColor(sib, RED);
2208                      x = parentOf(x);
2209                  } else {
2210                      if (colorOf(leftOf(sib)) == BLACK) {
# Line 1958 | Line 2255 | public class TreeMap<K,V>
2255          }
2256      }
2257  
1961
1962
2258      /**
2259       * Reconstitute the <tt>TreeMap</tt> instance from a stream (i.e.,
2260       * deserialize it).
# Line 1975 | Line 2270 | public class TreeMap<K,V>
2270          buildFromSorted(size, null, s, null);
2271      }
2272  
2273 <    /** Intended to be called only from TreeSet.readObject **/
2273 >    /** Intended to be called only from TreeSet.readObject */
2274      void readTreeSet(int size, java.io.ObjectInputStream s, V defaultVal)
2275          throws java.io.IOException, ClassNotFoundException {
2276          buildFromSorted(size, null, s, defaultVal);
2277      }
2278  
2279 <    /** Intended to be called only from TreeSet.addAll **/
2279 >    /** Intended to be called only from TreeSet.addAll */
2280      void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
2281          try {
2282              buildFromSorted(set.size(), set.iterator(), null, defaultVal);
# Line 2021 | Line 2316 | public class TreeMap<K,V>
2316       * @throws ClassNotFoundException propagated from readObject.
2317       *         This cannot occur if str is null.
2318       */
2319 <    private
2320 <    void buildFromSorted(int size, Iterator it,
2321 <                         java.io.ObjectInputStream str,
2027 <                         V defaultVal)
2319 >    private void buildFromSorted(int size, Iterator it,
2320 >                                 java.io.ObjectInputStream str,
2321 >                                 V defaultVal)
2322          throws  java.io.IOException, ClassNotFoundException {
2323          this.size = size;
2324 <        root =
2325 <            buildFromSorted(0, 0, size-1, computeRedLevel(size),
2032 <                            it, str, defaultVal);
2324 >        root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
2325 >                               it, str, defaultVal);
2326      }
2327  
2328      /**
2329       * Recursive "helper method" that does the real work of the
2330 <     * of the previous method.  Identically named parameters have
2330 >     * previous method.  Identically named parameters have
2331       * identical definitions.  Additional parameters are documented below.
2332       * It is assumed that the comparator and size fields of the TreeMap are
2333       * already set prior to calling this method.  (It ignores both fields.)
# Line 2066 | Line 2359 | public class TreeMap<K,V>
2359  
2360          if (hi < lo) return null;
2361  
2362 <        int mid = (lo + hi) / 2;
2362 >        int mid = (lo + hi) >>> 1;
2363  
2364          Entry<K,V> left  = null;
2365          if (lo < mid)

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines