jdk/src/share/classes/java/util/Collections.java
changeset 18818 a9ceff754226
parent 18794 17d9c2ec5e47
child 18822 4b6be7c19547
equal deleted inserted replaced
18815:5da35ed47cfa 18818:a9ceff754226
    25 
    25 
    26 package java.util;
    26 package java.util;
    27 import java.io.Serializable;
    27 import java.io.Serializable;
    28 import java.io.ObjectOutputStream;
    28 import java.io.ObjectOutputStream;
    29 import java.io.IOException;
    29 import java.io.IOException;
       
    30 import java.io.InvalidObjectException;
    30 import java.lang.reflect.Array;
    31 import java.lang.reflect.Array;
    31 import java.util.function.BiConsumer;
    32 import java.util.function.BiConsumer;
    32 import java.util.function.BiFunction;
    33 import java.util.function.BiFunction;
    33 import java.util.function.Consumer;
    34 import java.util.function.Consumer;
    34 import java.util.function.Function;
    35 import java.util.function.Function;
   136      * input array.  It is well-suited to merging two or more sorted arrays:
   137      * input array.  It is well-suited to merging two or more sorted arrays:
   137      * simply concatenate the arrays and sort the resulting array.
   138      * simply concatenate the arrays and sort the resulting array.
   138      *
   139      *
   139      * <p>The implementation was adapted from Tim Peters's list sort for Python
   140      * <p>The implementation was adapted from Tim Peters's list sort for Python
   140      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
   141      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
   141      * TimSort</a>).  It uses techiques from Peter McIlroy's "Optimistic
   142      * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
   142      * Sorting and Information Theoretic Complexity", in Proceedings of the
   143      * Sorting and Information Theoretic Complexity", in Proceedings of the
   143      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
   144      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
   144      * January 1993.
   145      * January 1993.
   145      *
   146      *
   146      * <p>This implementation dumps the specified list into an array, sorts
   147      * <p>This implementation dumps the specified list into an array, sorts
   197      * input array.  It is well-suited to merging two or more sorted arrays:
   198      * input array.  It is well-suited to merging two or more sorted arrays:
   198      * simply concatenate the arrays and sort the resulting array.
   199      * simply concatenate the arrays and sort the resulting array.
   199      *
   200      *
   200      * <p>The implementation was adapted from Tim Peters's list sort for Python
   201      * <p>The implementation was adapted from Tim Peters's list sort for Python
   201      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
   202      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
   202      * TimSort</a>).  It uses techiques from Peter McIlroy's "Optimistic
   203      * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
   203      * Sorting and Information Theoretic Complexity", in Proceedings of the
   204      * Sorting and Information Theoretic Complexity", in Proceedings of the
   204      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
   205      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
   205      * January 1993.
   206      * January 1993.
   206      *
   207      *
   207      * <p>This implementation dumps the specified list into an array, sorts
   208      * <p>This implementation dumps the specified list into an array, sorts
  1212         public E first()                   {return ss.first();}
  1213         public E first()                   {return ss.first();}
  1213         public E last()                    {return ss.last();}
  1214         public E last()                    {return ss.last();}
  1214     }
  1215     }
  1215 
  1216 
  1216     /**
  1217     /**
       
  1218      * Returns an unmodifiable view of the specified navigable set.  This method
       
  1219      * allows modules to provide users with "read-only" access to internal
       
  1220      * navigable sets.  Query operations on the returned navigable set "read
       
  1221      * through" to the specified navigable set.  Attempts to modify the returned
       
  1222      * navigable set, whether direct, via its iterator, or via its
       
  1223      * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
       
  1224      * an {@code UnsupportedOperationException}.<p>
       
  1225      *
       
  1226      * The returned navigable set will be serializable if the specified
       
  1227      * navigable set is serializable.
       
  1228      *
       
  1229      * @param s the navigable set for which an unmodifiable view is to be
       
  1230      *        returned
       
  1231      * @return an unmodifiable view of the specified navigable set
       
  1232      * @since 1.8
       
  1233      */
       
  1234     public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) {
       
  1235         return new UnmodifiableNavigableSet<>(s);
       
  1236     }
       
  1237 
       
  1238     /**
       
  1239      * Wraps a navigable set and disables all of the mutative operations.
       
  1240      *
       
  1241      * @param <E> type of elements
       
  1242      * @serial include
       
  1243      */
       
  1244     static class UnmodifiableNavigableSet<E>
       
  1245                              extends UnmodifiableSortedSet<E>
       
  1246                              implements NavigableSet<E>, Serializable {
       
  1247 
       
  1248         private static final long serialVersionUID = -6027448201786391929L;
       
  1249 
       
  1250         /**
       
  1251          * A singleton empty unmodifiable navigable set used for
       
  1252          * {@link #emptyNavigableSet()}.
       
  1253          *
       
  1254          * @param <E> type of elements, if there were any, and bounds
       
  1255          */
       
  1256         private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E>
       
  1257             implements Serializable {
       
  1258             private static final long serialVersionUID = -6291252904449939134L;
       
  1259 
       
  1260             public EmptyNavigableSet() {
       
  1261                 super(new TreeSet<E>());
       
  1262             }
       
  1263 
       
  1264             private Object readResolve()        { return EMPTY_NAVIGABLE_SET; }
       
  1265         }
       
  1266 
       
  1267         @SuppressWarnings("rawtypes")
       
  1268         private static final NavigableSet<?> EMPTY_NAVIGABLE_SET =
       
  1269                 new EmptyNavigableSet<>();
       
  1270 
       
  1271         /**
       
  1272          * The instance we are protecting.
       
  1273          */
       
  1274         private final NavigableSet<E> ns;
       
  1275 
       
  1276         UnmodifiableNavigableSet(NavigableSet<E> s)         {super(s); ns = s;}
       
  1277 
       
  1278         public E lower(E e)                             { return ns.lower(e); }
       
  1279         public E floor(E e)                             { return ns.floor(e); }
       
  1280         public E ceiling(E e)                         { return ns.ceiling(e); }
       
  1281         public E higher(E e)                           { return ns.higher(e); }
       
  1282         public E pollFirst()     { throw new UnsupportedOperationException(); }
       
  1283         public E pollLast()      { throw new UnsupportedOperationException(); }
       
  1284         public NavigableSet<E> descendingSet()
       
  1285                  { return new UnmodifiableNavigableSet<>(ns.descendingSet()); }
       
  1286         public Iterator<E> descendingIterator()
       
  1287                                          { return descendingSet().iterator(); }
       
  1288 
       
  1289         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
       
  1290             return new UnmodifiableNavigableSet<>(
       
  1291                 ns.subSet(fromElement, fromInclusive, toElement, toInclusive));
       
  1292         }
       
  1293 
       
  1294         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
       
  1295             return new UnmodifiableNavigableSet<>(
       
  1296                 ns.headSet(toElement, inclusive));
       
  1297         }
       
  1298 
       
  1299         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
       
  1300             return new UnmodifiableNavigableSet<>(
       
  1301                 ns.tailSet(fromElement, inclusive));
       
  1302         }
       
  1303     }
       
  1304 
       
  1305     /**
  1217      * Returns an unmodifiable view of the specified list.  This method allows
  1306      * Returns an unmodifiable view of the specified list.  This method allows
  1218      * modules to provide users with "read-only" access to internal
  1307      * modules to provide users with "read-only" access to internal
  1219      * lists.  Query operations on the returned list "read through" to the
  1308      * lists.  Query operations on the returned list "read through" to the
  1220      * specified list, and attempts to modify the returned list, whether
  1309      * specified list, and attempts to modify the returned list, whether
  1221      * direct or via its iterator, result in an
  1310      * direct or via its iterator, result in an
  1238      * @serial include
  1327      * @serial include
  1239      */
  1328      */
  1240     static class UnmodifiableList<E> extends UnmodifiableCollection<E>
  1329     static class UnmodifiableList<E> extends UnmodifiableCollection<E>
  1241                                   implements List<E> {
  1330                                   implements List<E> {
  1242         private static final long serialVersionUID = -283967356065247728L;
  1331         private static final long serialVersionUID = -283967356065247728L;
       
  1332 
  1243         final List<? extends E> list;
  1333         final List<? extends E> list;
  1244 
  1334 
  1245         UnmodifiableList(List<? extends E> list) {
  1335         UnmodifiableList(List<? extends E> list) {
  1246             super(list);
  1336             super(list);
  1247             this.list = list;
  1337             this.list = list;
  1680              * Map Entry when asked to perform an equality check.
  1770              * Map Entry when asked to perform an equality check.
  1681              */
  1771              */
  1682             private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
  1772             private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
  1683                 private Map.Entry<? extends K, ? extends V> e;
  1773                 private Map.Entry<? extends K, ? extends V> e;
  1684 
  1774 
  1685                 UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e) {this.e = e;}
  1775                 UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e)
       
  1776                         {this.e = Objects.requireNonNull(e);}
  1686 
  1777 
  1687                 public K getKey()        {return e.getKey();}
  1778                 public K getKey()        {return e.getKey();}
  1688                 public V getValue()      {return e.getValue();}
  1779                 public V getValue()      {return e.getValue();}
  1689                 public V setValue(V value) {
  1780                 public V setValue(V value) {
  1690                     throw new UnsupportedOperationException();
  1781                     throw new UnsupportedOperationException();
  1732           implements SortedMap<K,V>, Serializable {
  1823           implements SortedMap<K,V>, Serializable {
  1733         private static final long serialVersionUID = -8806743815996713206L;
  1824         private static final long serialVersionUID = -8806743815996713206L;
  1734 
  1825 
  1735         private final SortedMap<K, ? extends V> sm;
  1826         private final SortedMap<K, ? extends V> sm;
  1736 
  1827 
  1737         UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
  1828         UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m; }
  1738 
  1829         public Comparator<? super K> comparator()   { return sm.comparator(); }
  1739         public Comparator<? super K> comparator() {return sm.comparator();}
  1830         public SortedMap<K,V> subMap(K fromKey, K toKey)
  1740 
  1831              { return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); }
  1741         public SortedMap<K,V> subMap(K fromKey, K toKey) {
  1832         public SortedMap<K,V> headMap(K toKey)
  1742             return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));
  1833                      { return new UnmodifiableSortedMap<>(sm.headMap(toKey)); }
  1743         }
  1834         public SortedMap<K,V> tailMap(K fromKey)
  1744         public SortedMap<K,V> headMap(K toKey) {
  1835                    { return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); }
  1745             return new UnmodifiableSortedMap<>(sm.headMap(toKey));
  1836         public K firstKey()                           { return sm.firstKey(); }
  1746         }
  1837         public K lastKey()                             { return sm.lastKey(); }
  1747         public SortedMap<K,V> tailMap(K fromKey) {
  1838     }
  1748             return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));
  1839 
  1749         }
  1840     /**
  1750 
  1841      * Returns an unmodifiable view of the specified navigable map.  This method
  1751         public K firstKey()           {return sm.firstKey();}
  1842      * allows modules to provide users with "read-only" access to internal
  1752         public K lastKey()            {return sm.lastKey();}
  1843      * navigable maps.  Query operations on the returned navigable map "read
  1753     }
  1844      * through" to the specified navigable map.  Attempts to modify the returned
  1754 
  1845      * navigable map, whether direct, via its collection views, or via its
       
  1846      * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in
       
  1847      * an {@code UnsupportedOperationException}.<p>
       
  1848      *
       
  1849      * The returned navigable map will be serializable if the specified
       
  1850      * navigable map is serializable.
       
  1851      *
       
  1852      * @param m the navigable map for which an unmodifiable view is to be
       
  1853      *        returned
       
  1854      * @return an unmodifiable view of the specified navigable map
       
  1855      * @since 1.8
       
  1856      */
       
  1857     public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {
       
  1858         return new UnmodifiableNavigableMap<>(m);
       
  1859     }
       
  1860 
       
  1861     /**
       
  1862      * @serial include
       
  1863      */
       
  1864     static class UnmodifiableNavigableMap<K,V>
       
  1865           extends UnmodifiableSortedMap<K,V>
       
  1866           implements NavigableMap<K,V>, Serializable {
       
  1867         private static final long serialVersionUID = -4858195264774772197L;
       
  1868 
       
  1869         /**
       
  1870          * A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve
       
  1871          * to preserve singleton property.
       
  1872          *
       
  1873          * @param <K> type of keys, if there were any, and of bounds
       
  1874          * @param <V> type of values, if there were any
       
  1875          */
       
  1876         private static class EmptyNavigableMap<K,V> extends UnmodifiableNavigableMap<K,V>
       
  1877             implements Serializable {
       
  1878 
       
  1879             private static final long serialVersionUID = -2239321462712562324L;
       
  1880 
       
  1881             EmptyNavigableMap()                       { super(new TreeMap()); }
       
  1882 
       
  1883             @Override
       
  1884             public NavigableSet<K> navigableKeySet()
       
  1885                                                 { return emptyNavigableSet(); }
       
  1886 
       
  1887             private Object readResolve()        { return EMPTY_NAVIGABLE_MAP; }
       
  1888         }
       
  1889 
       
  1890         /**
       
  1891          * Singleton for {@link emptyNavigableMap()} which is also immutable.
       
  1892          */
       
  1893         private static final EmptyNavigableMap<?,?> EMPTY_NAVIGABLE_MAP =
       
  1894             new EmptyNavigableMap<>();
       
  1895 
       
  1896         /**
       
  1897          * The instance we wrap and protect.
       
  1898          */
       
  1899         private final NavigableMap<K, ? extends V> nm;
       
  1900 
       
  1901         UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m)
       
  1902                                                             {super(m); nm = m;}
       
  1903 
       
  1904         public K lowerKey(K key)                   { return nm.lowerKey(key); }
       
  1905         public K floorKey(K key)                   { return nm.floorKey(key); }
       
  1906         public K ceilingKey(K key)               { return nm.ceilingKey(key); }
       
  1907         public K higherKey(K key)                 { return nm.higherKey(key); }
       
  1908 
       
  1909         public Entry<K, V> lowerEntry(K key) {
       
  1910             Entry<K,V> lower = (Entry<K, V>) nm.lowerEntry(key);
       
  1911             return (null != lower)
       
  1912                 ? new UnmodifiableEntrySet.UnmodifiableEntry(lower)
       
  1913                 : null;
       
  1914         }
       
  1915 
       
  1916         public Entry<K, V> floorEntry(K key) {
       
  1917             Entry<K,V> floor = (Entry<K, V>) nm.floorEntry(key);
       
  1918             return (null != floor)
       
  1919                 ? new UnmodifiableEntrySet.UnmodifiableEntry(floor)
       
  1920                 : null;
       
  1921         }
       
  1922 
       
  1923         public Entry<K, V> ceilingEntry(K key) {
       
  1924             Entry<K,V> ceiling = (Entry<K, V>) nm.ceilingEntry(key);
       
  1925             return (null != ceiling)
       
  1926                 ? new UnmodifiableEntrySet.UnmodifiableEntry(ceiling)
       
  1927                 : null;
       
  1928         }
       
  1929 
       
  1930 
       
  1931         public Entry<K, V> higherEntry(K key) {
       
  1932             Entry<K,V> higher = (Entry<K, V>) nm.higherEntry(key);
       
  1933             return (null != higher)
       
  1934                 ? new UnmodifiableEntrySet.UnmodifiableEntry(higher)
       
  1935                 : null;
       
  1936         }
       
  1937 
       
  1938         public Entry<K, V> firstEntry() {
       
  1939             Entry<K,V> first = (Entry<K, V>) nm.firstEntry();
       
  1940             return (null != first)
       
  1941                 ? new UnmodifiableEntrySet.UnmodifiableEntry(first)
       
  1942                 : null;
       
  1943         }
       
  1944 
       
  1945         public Entry<K, V> lastEntry() {
       
  1946             Entry<K,V> last = (Entry<K, V>) nm.lastEntry();
       
  1947             return (null != last)
       
  1948                 ? new UnmodifiableEntrySet.UnmodifiableEntry(last)
       
  1949                 : null;
       
  1950         }
       
  1951 
       
  1952         public Entry<K, V> pollFirstEntry()
       
  1953                                  { throw new UnsupportedOperationException(); }
       
  1954         public Entry<K, V> pollLastEntry()
       
  1955                                  { throw new UnsupportedOperationException(); }
       
  1956         public NavigableMap<K, V> descendingMap()
       
  1957                        { return unmodifiableNavigableMap(nm.descendingMap()); }
       
  1958         public NavigableSet<K> navigableKeySet()
       
  1959                      { return unmodifiableNavigableSet(nm.navigableKeySet()); }
       
  1960         public NavigableSet<K> descendingKeySet()
       
  1961                     { return unmodifiableNavigableSet(nm.descendingKeySet()); }
       
  1962 
       
  1963         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
       
  1964             return unmodifiableNavigableMap(
       
  1965                 nm.subMap(fromKey, fromInclusive, toKey, toInclusive));
       
  1966         }
       
  1967 
       
  1968         public NavigableMap<K, V> headMap(K toKey, boolean inclusive)
       
  1969              { return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); }
       
  1970         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)
       
  1971            { return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); }
       
  1972     }
  1755 
  1973 
  1756     // Synch Wrappers
  1974     // Synch Wrappers
  1757 
  1975 
  1758     /**
  1976     /**
  1759      * Returns a synchronized (thread-safe) collection backed by the specified
  1977      * Returns a synchronized (thread-safe) collection backed by the specified
  1803 
  2021 
  1804         final Collection<E> c;  // Backing Collection
  2022         final Collection<E> c;  // Backing Collection
  1805         final Object mutex;     // Object on which to synchronize
  2023         final Object mutex;     // Object on which to synchronize
  1806 
  2024 
  1807         SynchronizedCollection(Collection<E> c) {
  2025         SynchronizedCollection(Collection<E> c) {
  1808             if (c==null)
  2026             this.c = Objects.requireNonNull(c);
  1809                 throw new NullPointerException();
       
  1810             this.c = c;
       
  1811             mutex = this;
  2027             mutex = this;
  1812         }
  2028         }
       
  2029 
  1813         SynchronizedCollection(Collection<E> c, Object mutex) {
  2030         SynchronizedCollection(Collection<E> c, Object mutex) {
  1814             this.c = c;
  2031             this.c = Objects.requireNonNull(c);
  1815             this.mutex = mutex;
  2032             this.mutex = Objects.requireNonNull(mutex);
  1816         }
  2033         }
  1817 
  2034 
  1818         public int size() {
  2035         public int size() {
  1819             synchronized (mutex) {return c.size();}
  2036             synchronized (mutex) {return c.size();}
  1820         }
  2037         }
  2025             synchronized (mutex) {return ss.last();}
  2242             synchronized (mutex) {return ss.last();}
  2026         }
  2243         }
  2027     }
  2244     }
  2028 
  2245 
  2029     /**
  2246     /**
       
  2247      * Returns a synchronized (thread-safe) navigable set backed by the
       
  2248      * specified navigable set.  In order to guarantee serial access, it is
       
  2249      * critical that <strong>all</strong> access to the backing navigable set is
       
  2250      * accomplished through the returned navigable set (or its views).<p>
       
  2251      *
       
  2252      * It is imperative that the user manually synchronize on the returned
       
  2253      * navigable set when iterating over it or any of its {@code subSet},
       
  2254      * {@code headSet}, or {@code tailSet} views.
       
  2255      * <pre>
       
  2256      *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
       
  2257      *      ...
       
  2258      *  synchronized (s) {
       
  2259      *      Iterator i = s.iterator(); // Must be in the synchronized block
       
  2260      *      while (i.hasNext())
       
  2261      *          foo(i.next());
       
  2262      *  }
       
  2263      * </pre>
       
  2264      * or:
       
  2265      * <pre>
       
  2266      *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
       
  2267      *  NavigableSet s2 = s.headSet(foo, true);
       
  2268      *      ...
       
  2269      *  synchronized (s) {  // Note: s, not s2!!!
       
  2270      *      Iterator i = s2.iterator(); // Must be in the synchronized block
       
  2271      *      while (i.hasNext())
       
  2272      *          foo(i.next());
       
  2273      *  }
       
  2274      * </pre>
       
  2275      * Failure to follow this advice may result in non-deterministic behavior.
       
  2276      *
       
  2277      * <p>The returned navigable set will be serializable if the specified
       
  2278      * navigable set is serializable.
       
  2279      *
       
  2280      * @param  s the navigable set to be "wrapped" in a synchronized navigable
       
  2281      * set
       
  2282      * @return a synchronized view of the specified navigable set
       
  2283      * @since 1.8
       
  2284      */
       
  2285     public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) {
       
  2286         return new SynchronizedNavigableSet<>(s);
       
  2287     }
       
  2288 
       
  2289     /**
       
  2290      * @serial include
       
  2291      */
       
  2292     static class SynchronizedNavigableSet<E>
       
  2293         extends SynchronizedSortedSet<E>
       
  2294         implements NavigableSet<E>
       
  2295     {
       
  2296         private static final long serialVersionUID = -5505529816273629798L;
       
  2297 
       
  2298         private final NavigableSet<E> ns;
       
  2299 
       
  2300         SynchronizedNavigableSet(NavigableSet<E> s) {
       
  2301             super(s);
       
  2302             ns = s;
       
  2303         }
       
  2304 
       
  2305         SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) {
       
  2306             super(s, mutex);
       
  2307             ns = s;
       
  2308         }
       
  2309         public E lower(E e)      { synchronized (mutex) {return ns.lower(e);} }
       
  2310         public E floor(E e)      { synchronized (mutex) {return ns.floor(e);} }
       
  2311         public E ceiling(E e)  { synchronized (mutex) {return ns.ceiling(e);} }
       
  2312         public E higher(E e)    { synchronized (mutex) {return ns.higher(e);} }
       
  2313         public E pollFirst()  { synchronized (mutex) {return ns.pollFirst();} }
       
  2314         public E pollLast()    { synchronized (mutex) {return ns.pollLast();} }
       
  2315 
       
  2316         public NavigableSet<E> descendingSet() {
       
  2317             synchronized (mutex) {
       
  2318                 return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex);
       
  2319             }
       
  2320         }
       
  2321 
       
  2322         public Iterator<E> descendingIterator()
       
  2323                  { synchronized (mutex) { return descendingSet().iterator(); } }
       
  2324 
       
  2325         public NavigableSet<E> subSet(E fromElement, E toElement) {
       
  2326             synchronized (mutex) {
       
  2327                 return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex);
       
  2328             }
       
  2329         }
       
  2330         public NavigableSet<E> headSet(E toElement) {
       
  2331             synchronized (mutex) {
       
  2332                 return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex);
       
  2333             }
       
  2334         }
       
  2335         public NavigableSet<E> tailSet(E fromElement) {
       
  2336             synchronized (mutex) {
       
  2337                 return new SynchronizedNavigableSet(ns.tailSet(fromElement, true), mutex);
       
  2338             }
       
  2339         }
       
  2340 
       
  2341         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
       
  2342             synchronized (mutex) {
       
  2343                 return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex);
       
  2344             }
       
  2345         }
       
  2346 
       
  2347         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
       
  2348             synchronized (mutex) {
       
  2349                 return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex);
       
  2350             }
       
  2351         }
       
  2352 
       
  2353         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
       
  2354             synchronized (mutex) {
       
  2355                 return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive));
       
  2356             }
       
  2357         }
       
  2358     }
       
  2359 
       
  2360     /**
  2030      * Returns a synchronized (thread-safe) list backed by the specified
  2361      * Returns a synchronized (thread-safe) list backed by the specified
  2031      * list.  In order to guarantee serial access, it is critical that
  2362      * list.  In order to guarantee serial access, it is critical that
  2032      * <strong>all</strong> access to the backing list is accomplished
  2363      * <strong>all</strong> access to the backing list is accomplished
  2033      * through the returned list.<p>
  2364      * through the returned list.<p>
  2034      *
  2365      *
  2233 
  2564 
  2234         private final Map<K,V> m;     // Backing Map
  2565         private final Map<K,V> m;     // Backing Map
  2235         final Object      mutex;        // Object on which to synchronize
  2566         final Object      mutex;        // Object on which to synchronize
  2236 
  2567 
  2237         SynchronizedMap(Map<K,V> m) {
  2568         SynchronizedMap(Map<K,V> m) {
  2238             if (m==null)
  2569             this.m = Objects.requireNonNull(m);
  2239                 throw new NullPointerException();
       
  2240             this.m = m;
       
  2241             mutex = this;
  2570             mutex = this;
  2242         }
  2571         }
  2243 
  2572 
  2244         SynchronizedMap(Map<K,V> m, Object mutex) {
  2573         SynchronizedMap(Map<K,V> m, Object mutex) {
  2245             this.m = m;
  2574             this.m = m;
  2414      */
  2743      */
  2415     public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
  2744     public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
  2416         return new SynchronizedSortedMap<>(m);
  2745         return new SynchronizedSortedMap<>(m);
  2417     }
  2746     }
  2418 
  2747 
  2419 
       
  2420     /**
  2748     /**
  2421      * @serial include
  2749      * @serial include
  2422      */
  2750      */
  2423     static class SynchronizedSortedMap<K,V>
  2751     static class SynchronizedSortedMap<K,V>
  2424         extends SynchronizedMap<K,V>
  2752         extends SynchronizedMap<K,V>
  2461         public K firstKey() {
  2789         public K firstKey() {
  2462             synchronized (mutex) {return sm.firstKey();}
  2790             synchronized (mutex) {return sm.firstKey();}
  2463         }
  2791         }
  2464         public K lastKey() {
  2792         public K lastKey() {
  2465             synchronized (mutex) {return sm.lastKey();}
  2793             synchronized (mutex) {return sm.lastKey();}
       
  2794         }
       
  2795     }
       
  2796 
       
  2797     /**
       
  2798      * Returns a synchronized (thread-safe) navigable map backed by the
       
  2799      * specified navigable map.  In order to guarantee serial access, it is
       
  2800      * critical that <strong>all</strong> access to the backing navigable map is
       
  2801      * accomplished through the returned navigable map (or its views).<p>
       
  2802      *
       
  2803      * It is imperative that the user manually synchronize on the returned
       
  2804      * navigable map when iterating over any of its collection views, or the
       
  2805      * collections views of any of its {@code subMap}, {@code headMap} or
       
  2806      * {@code tailMap} views.
       
  2807      * <pre>
       
  2808      *  NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
       
  2809      *      ...
       
  2810      *  Set s = m.keySet();  // Needn't be in synchronized block
       
  2811      *      ...
       
  2812      *  synchronized (m) {  // Synchronizing on m, not s!
       
  2813      *      Iterator i = s.iterator(); // Must be in synchronized block
       
  2814      *      while (i.hasNext())
       
  2815      *          foo(i.next());
       
  2816      *  }
       
  2817      * </pre>
       
  2818      * or:
       
  2819      * <pre>
       
  2820      *  NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
       
  2821      *  NavigableMap m2 = m.subMap(foo, true, bar, false);
       
  2822      *      ...
       
  2823      *  Set s2 = m2.keySet();  // Needn't be in synchronized block
       
  2824      *      ...
       
  2825      *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
       
  2826      *      Iterator i = s.iterator(); // Must be in synchronized block
       
  2827      *      while (i.hasNext())
       
  2828      *          foo(i.next());
       
  2829      *  }
       
  2830      * </pre>
       
  2831      * Failure to follow this advice may result in non-deterministic behavior.
       
  2832      *
       
  2833      * <p>The returned navigable map will be serializable if the specified
       
  2834      * navigable map is serializable.
       
  2835      *
       
  2836      * @param  m the navigable map to be "wrapped" in a synchronized navigable
       
  2837      *              map
       
  2838      * @return a synchronized view of the specified navigable map.
       
  2839      * @since 1.8
       
  2840      */
       
  2841     public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) {
       
  2842         return new SynchronizedNavigableMap<>(m);
       
  2843     }
       
  2844 
       
  2845     /**
       
  2846      * A synchronized NavigableMap.
       
  2847      *
       
  2848      * @serial include
       
  2849      */
       
  2850     static class SynchronizedNavigableMap<K,V>
       
  2851         extends SynchronizedSortedMap<K,V>
       
  2852         implements NavigableMap<K,V>
       
  2853     {
       
  2854         private static final long serialVersionUID = 699392247599746807L;
       
  2855 
       
  2856         private final NavigableMap<K,V> nm;
       
  2857 
       
  2858         SynchronizedNavigableMap(NavigableMap<K,V> m) {
       
  2859             super(m);
       
  2860             nm = m;
       
  2861         }
       
  2862         SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) {
       
  2863             super(m, mutex);
       
  2864             nm = m;
       
  2865         }
       
  2866 
       
  2867         public Entry<K, V> lowerEntry(K key)
       
  2868                         { synchronized (mutex) { return nm.lowerEntry(key); } }
       
  2869         public K lowerKey(K key)
       
  2870                           { synchronized (mutex) { return nm.lowerKey(key); } }
       
  2871         public Entry<K, V> floorEntry(K key)
       
  2872                         { synchronized (mutex) { return nm.floorEntry(key); } }
       
  2873         public K floorKey(K key)
       
  2874                           { synchronized (mutex) { return nm.floorKey(key); } }
       
  2875         public Entry<K, V> ceilingEntry(K key)
       
  2876                       { synchronized (mutex) { return nm.ceilingEntry(key); } }
       
  2877         public K ceilingKey(K key)
       
  2878                         { synchronized (mutex) { return nm.ceilingKey(key); } }
       
  2879         public Entry<K, V> higherEntry(K key)
       
  2880                        { synchronized (mutex) { return nm.higherEntry(key); } }
       
  2881         public K higherKey(K key)
       
  2882                          { synchronized (mutex) { return nm.higherKey(key); } }
       
  2883         public Entry<K, V> firstEntry()
       
  2884                            { synchronized (mutex) { return nm.firstEntry(); } }
       
  2885         public Entry<K, V> lastEntry()
       
  2886                             { synchronized (mutex) { return nm.lastEntry(); } }
       
  2887         public Entry<K, V> pollFirstEntry()
       
  2888                        { synchronized (mutex) { return nm.pollFirstEntry(); } }
       
  2889         public Entry<K, V> pollLastEntry()
       
  2890                         { synchronized (mutex) { return nm.pollLastEntry(); } }
       
  2891 
       
  2892         public NavigableMap<K, V> descendingMap() {
       
  2893             synchronized (mutex) {
       
  2894                 return
       
  2895                     new SynchronizedNavigableMap(nm.descendingMap(), mutex);
       
  2896             }
       
  2897         }
       
  2898 
       
  2899         public NavigableSet<K> keySet() {
       
  2900             return navigableKeySet();
       
  2901         }
       
  2902 
       
  2903         public NavigableSet<K> navigableKeySet() {
       
  2904             synchronized (mutex) {
       
  2905                 return new SynchronizedNavigableSet(nm.navigableKeySet(), mutex);
       
  2906             }
       
  2907         }
       
  2908 
       
  2909         public NavigableSet<K> descendingKeySet() {
       
  2910             synchronized (mutex) {
       
  2911                 return new SynchronizedNavigableSet(nm.descendingKeySet(), mutex);
       
  2912             }
       
  2913         }
       
  2914 
       
  2915 
       
  2916         public SortedMap<K,V> subMap(K fromKey, K toKey) {
       
  2917             synchronized (mutex) {
       
  2918                 return new SynchronizedNavigableMap<>(
       
  2919                     nm.subMap(fromKey, true, toKey, false), mutex);
       
  2920             }
       
  2921         }
       
  2922         public SortedMap<K,V> headMap(K toKey) {
       
  2923             synchronized (mutex) {
       
  2924                 return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex);
       
  2925             }
       
  2926         }
       
  2927         public SortedMap<K,V> tailMap(K fromKey) {
       
  2928             synchronized (mutex) {
       
  2929                return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex);
       
  2930             }
       
  2931         }
       
  2932 
       
  2933         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
       
  2934             synchronized (mutex) {
       
  2935                 return new SynchronizedNavigableMap(
       
  2936                     nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex);
       
  2937             }
       
  2938         }
       
  2939 
       
  2940         public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
       
  2941             synchronized (mutex) {
       
  2942                 return new SynchronizedNavigableMap(
       
  2943                         nm.headMap(toKey, inclusive), mutex);
       
  2944             }
       
  2945         }
       
  2946 
       
  2947         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
       
  2948             synchronized (mutex) {
       
  2949                 return new SynchronizedNavigableMap(
       
  2950                     nm.tailMap(fromKey, inclusive), mutex);
       
  2951             }
  2466         }
  2952         }
  2467     }
  2953     }
  2468 
  2954 
  2469     // Dynamically typesafe collection wrappers
  2955     // Dynamically typesafe collection wrappers
  2470 
  2956 
  2495      * as to the real source of the problem.  If the problem is reproducible,
  2981      * as to the real source of the problem.  If the problem is reproducible,
  2496      * one can quickly determine its source by temporarily modifying the
  2982      * one can quickly determine its source by temporarily modifying the
  2497      * program to wrap the collection with a dynamically typesafe view.
  2983      * program to wrap the collection with a dynamically typesafe view.
  2498      * For example, this declaration:
  2984      * For example, this declaration:
  2499      *  <pre> {@code
  2985      *  <pre> {@code
  2500      *     Collection<String> c = new HashSet<String>();
  2986      *     Collection<String> c = new HashSet<>();
  2501      * }</pre>
  2987      * }</pre>
  2502      * may be replaced temporarily by this one:
  2988      * may be replaced temporarily by this one:
  2503      *  <pre> {@code
  2989      *  <pre> {@code
  2504      *     Collection<String> c = Collections.checkedCollection(
  2990      *     Collection<String> c = Collections.checkedCollection(
  2505      *         new HashSet<String>(), String.class);
  2991      *         new HashSet<>(), String.class);
  2506      * }</pre>
  2992      * }</pre>
  2507      * Running the program again will cause it to fail at the point where
  2993      * Running the program again will cause it to fail at the point where
  2508      * an incorrectly typed element is inserted into the collection, clearly
  2994      * an incorrectly typed element is inserted into the collection, clearly
  2509      * identifying the source of the problem.  Once the problem is fixed, the
  2995      * identifying the source of the problem.  Once the problem is fixed, the
  2510      * modified declaration may be reverted back to the original.
  2996      * modified declaration may be reverted back to the original.
  2786      */
  3272      */
  2787     static class CheckedSortedSet<E> extends CheckedSet<E>
  3273     static class CheckedSortedSet<E> extends CheckedSet<E>
  2788         implements SortedSet<E>, Serializable
  3274         implements SortedSet<E>, Serializable
  2789     {
  3275     {
  2790         private static final long serialVersionUID = 1599911165492914959L;
  3276         private static final long serialVersionUID = 1599911165492914959L;
       
  3277 
  2791         private final SortedSet<E> ss;
  3278         private final SortedSet<E> ss;
  2792 
  3279 
  2793         CheckedSortedSet(SortedSet<E> s, Class<E> type) {
  3280         CheckedSortedSet(SortedSet<E> s, Class<E> type) {
  2794             super(s, type);
  3281             super(s, type);
  2795             ss = s;
  3282             ss = s;
  2805         public SortedSet<E> headSet(E toElement) {
  3292         public SortedSet<E> headSet(E toElement) {
  2806             return checkedSortedSet(ss.headSet(toElement), type);
  3293             return checkedSortedSet(ss.headSet(toElement), type);
  2807         }
  3294         }
  2808         public SortedSet<E> tailSet(E fromElement) {
  3295         public SortedSet<E> tailSet(E fromElement) {
  2809             return checkedSortedSet(ss.tailSet(fromElement), type);
  3296             return checkedSortedSet(ss.tailSet(fromElement), type);
       
  3297         }
       
  3298     }
       
  3299 
       
  3300 /**
       
  3301      * Returns a dynamically typesafe view of the specified navigable set.
       
  3302      * Any attempt to insert an element of the wrong type will result in an
       
  3303      * immediate {@link ClassCastException}.  Assuming a navigable set
       
  3304      * contains no incorrectly typed elements prior to the time a
       
  3305      * dynamically typesafe view is generated, and that all subsequent
       
  3306      * access to the navigable set takes place through the view, it is
       
  3307      * <em>guaranteed</em> that the navigable set cannot contain an incorrectly
       
  3308      * typed element.
       
  3309      *
       
  3310      * <p>A discussion of the use of dynamically typesafe views may be
       
  3311      * found in the documentation for the {@link #checkedCollection
       
  3312      * checkedCollection} method.
       
  3313      *
       
  3314      * <p>The returned navigable set will be serializable if the specified
       
  3315      * navigable set is serializable.
       
  3316      *
       
  3317      * <p>Since {@code null} is considered to be a value of any reference
       
  3318      * type, the returned navigable set permits insertion of null elements
       
  3319      * whenever the backing sorted set does.
       
  3320      *
       
  3321      * @param s the navigable set for which a dynamically typesafe view is to be
       
  3322      *          returned
       
  3323      * @param type the type of element that {@code s} is permitted to hold
       
  3324      * @return a dynamically typesafe view of the specified navigable set
       
  3325      * @since 1.8
       
  3326      */
       
  3327     public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,
       
  3328                                                     Class<E> type) {
       
  3329         return new CheckedNavigableSet<>(s, type);
       
  3330     }
       
  3331 
       
  3332     /**
       
  3333      * @serial include
       
  3334      */
       
  3335     static class CheckedNavigableSet<E> extends CheckedSortedSet<E>
       
  3336         implements NavigableSet<E>, Serializable
       
  3337     {
       
  3338         private static final long serialVersionUID = -5429120189805438922L;
       
  3339 
       
  3340         private final NavigableSet<E> ns;
       
  3341 
       
  3342         CheckedNavigableSet(NavigableSet<E> s, Class<E> type) {
       
  3343             super(s, type);
       
  3344             ns = s;
       
  3345         }
       
  3346 
       
  3347         public E lower(E e)                             { return ns.lower(e); }
       
  3348         public E floor(E e)                             { return ns.floor(e); }
       
  3349         public E ceiling(E e)                         { return ns.ceiling(e); }
       
  3350         public E higher(E e)                           { return ns.higher(e); }
       
  3351         public E pollFirst()                         { return ns.pollFirst(); }
       
  3352         public E pollLast()                            {return ns.pollLast(); }
       
  3353         public NavigableSet<E> descendingSet()
       
  3354                       { return checkedNavigableSet(ns.descendingSet(), type); }
       
  3355         public Iterator<E> descendingIterator()
       
  3356             {return checkedNavigableSet(ns.descendingSet(), type).iterator(); }
       
  3357 
       
  3358         public NavigableSet<E> subSet(E fromElement, E toElement) {
       
  3359             return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type);
       
  3360         }
       
  3361         public NavigableSet<E> headSet(E toElement) {
       
  3362             return checkedNavigableSet(ns.headSet(toElement, false), type);
       
  3363         }
       
  3364         public NavigableSet<E> tailSet(E fromElement) {
       
  3365             return checkedNavigableSet(ns.tailSet(fromElement, true), type);
       
  3366         }
       
  3367 
       
  3368         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
       
  3369             return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type);
       
  3370         }
       
  3371 
       
  3372         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
       
  3373             return checkedNavigableSet(ns.headSet(toElement, inclusive), type);
       
  3374         }
       
  3375 
       
  3376         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
       
  3377             return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type);
  2810         }
  3378         }
  2811     }
  3379     }
  2812 
  3380 
  2813     /**
  3381     /**
  2814      * Returns a dynamically typesafe view of the specified list.
  3382      * Returns a dynamically typesafe view of the specified list.
  3020             return "Attempt to insert " + value.getClass() +
  3588             return "Attempt to insert " + value.getClass() +
  3021                     " value into map with value type " + valueType;
  3589                     " value into map with value type " + valueType;
  3022         }
  3590         }
  3023 
  3591 
  3024         CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
  3592         CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
  3025             if (m == null || keyType == null || valueType == null)
  3593             this.m = Objects.requireNonNull(m);
  3026                 throw new NullPointerException();
  3594             this.keyType = Objects.requireNonNull(keyType);
  3027             this.m = m;
  3595             this.valueType = Objects.requireNonNull(valueType);
  3028             this.keyType = keyType;
       
  3029             this.valueType = valueType;
       
  3030         }
  3596         }
  3031 
  3597 
  3032         public int size()                      { return m.size(); }
  3598         public int size()                      { return m.size(); }
  3033         public boolean isEmpty()               { return m.isEmpty(); }
  3599         public boolean isEmpty()               { return m.isEmpty(); }
  3034         public boolean containsKey(Object key) { return m.containsKey(key); }
  3600         public boolean containsKey(Object key) { return m.containsKey(key); }
  3301             private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {
  3867             private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {
  3302                 private final Map.Entry<K, V> e;
  3868                 private final Map.Entry<K, V> e;
  3303                 private final Class<T> valueType;
  3869                 private final Class<T> valueType;
  3304 
  3870 
  3305                 CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
  3871                 CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
  3306                     this.e = e;
  3872                     this.e = Objects.requireNonNull(e);
  3307                     this.valueType = valueType;
  3873                     this.valueType = Objects.requireNonNull(valueType);
  3308                 }
  3874                 }
  3309 
  3875 
  3310                 public K getKey()        { return e.getKey(); }
  3876                 public K getKey()        { return e.getKey(); }
  3311                 public V getValue()      { return e.getValue(); }
  3877                 public V getValue()      { return e.getValue(); }
  3312                 public int hashCode()    { return e.hashCode(); }
  3878                 public int hashCode()    { return e.hashCode(); }
  3405         public SortedMap<K,V> tailMap(K fromKey) {
  3971         public SortedMap<K,V> tailMap(K fromKey) {
  3406             return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);
  3972             return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);
  3407         }
  3973         }
  3408     }
  3974     }
  3409 
  3975 
       
  3976     /**
       
  3977      * Returns a dynamically typesafe view of the specified navigable map.
       
  3978      * Any attempt to insert a mapping whose key or value have the wrong
       
  3979      * type will result in an immediate {@link ClassCastException}.
       
  3980      * Similarly, any attempt to modify the value currently associated with
       
  3981      * a key will result in an immediate {@link ClassCastException},
       
  3982      * whether the modification is attempted directly through the map
       
  3983      * itself, or through a {@link Map.Entry} instance obtained from the
       
  3984      * map's {@link Map#entrySet() entry set} view.
       
  3985      *
       
  3986      * <p>Assuming a map contains no incorrectly typed keys or values
       
  3987      * prior to the time a dynamically typesafe view is generated, and
       
  3988      * that all subsequent access to the map takes place through the view
       
  3989      * (or one of its collection views), it is <em>guaranteed</em> that the
       
  3990      * map cannot contain an incorrectly typed key or value.
       
  3991      *
       
  3992      * <p>A discussion of the use of dynamically typesafe views may be
       
  3993      * found in the documentation for the {@link #checkedCollection
       
  3994      * checkedCollection} method.
       
  3995      *
       
  3996      * <p>The returned map will be serializable if the specified map is
       
  3997      * serializable.
       
  3998      *
       
  3999      * <p>Since {@code null} is considered to be a value of any reference
       
  4000      * type, the returned map permits insertion of null keys or values
       
  4001      * whenever the backing map does.
       
  4002      *
       
  4003      * @param <K> type of map keys
       
  4004      * @param <V> type of map values
       
  4005      * @param m the map for which a dynamically typesafe view is to be
       
  4006      *          returned
       
  4007      * @param keyType the type of key that {@code m} is permitted to hold
       
  4008      * @param valueType the type of value that {@code m} is permitted to hold
       
  4009      * @return a dynamically typesafe view of the specified map
       
  4010      * @since 1.8
       
  4011      */
       
  4012     public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m,
       
  4013                                                         Class<K> keyType,
       
  4014                                                         Class<V> valueType) {
       
  4015         return new CheckedNavigableMap<>(m, keyType, valueType);
       
  4016     }
       
  4017 
       
  4018     /**
       
  4019      * @serial include
       
  4020      */
       
  4021     static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V>
       
  4022         implements NavigableMap<K,V>, Serializable
       
  4023     {
       
  4024         private static final long serialVersionUID = -4852462692372534096L;
       
  4025 
       
  4026         private final NavigableMap<K, V> nm;
       
  4027 
       
  4028         CheckedNavigableMap(NavigableMap<K, V> m,
       
  4029                          Class<K> keyType, Class<V> valueType) {
       
  4030             super(m, keyType, valueType);
       
  4031             nm = m;
       
  4032         }
       
  4033 
       
  4034         public Comparator<? super K> comparator()   { return nm.comparator(); }
       
  4035         public K firstKey()                           { return nm.firstKey(); }
       
  4036         public K lastKey()                             { return nm.lastKey(); }
       
  4037 
       
  4038         public Entry<K, V> lowerEntry(K key) {
       
  4039             Entry<K,V> lower = nm.lowerEntry(key);
       
  4040             return (null != lower)
       
  4041                 ? new CheckedMap.CheckedEntrySet.CheckedEntry(lower, valueType)
       
  4042                 : null;
       
  4043         }
       
  4044 
       
  4045         public K lowerKey(K key)                   { return nm.lowerKey(key); }
       
  4046 
       
  4047         public Entry<K, V> floorEntry(K key) {
       
  4048             Entry<K,V> floor = nm.floorEntry(key);
       
  4049             return (null != floor)
       
  4050                 ? new CheckedMap.CheckedEntrySet.CheckedEntry(floor, valueType)
       
  4051                 : null;
       
  4052         }
       
  4053 
       
  4054         public K floorKey(K key)                   { return nm.floorKey(key); }
       
  4055 
       
  4056         public Entry<K, V> ceilingEntry(K key) {
       
  4057             Entry<K,V> ceiling = nm.ceilingEntry(key);
       
  4058             return (null != ceiling)
       
  4059                 ? new CheckedMap.CheckedEntrySet.CheckedEntry(ceiling, valueType)
       
  4060                 : null;
       
  4061         }
       
  4062 
       
  4063         public K ceilingKey(K key)               { return nm.ceilingKey(key); }
       
  4064 
       
  4065         public Entry<K, V> higherEntry(K key) {
       
  4066             Entry<K,V> higher = nm.higherEntry(key);
       
  4067             return (null != higher)
       
  4068                 ? new CheckedMap.CheckedEntrySet.CheckedEntry(higher, valueType)
       
  4069                 : null;
       
  4070         }
       
  4071 
       
  4072         public K higherKey(K key)                 { return nm.higherKey(key); }
       
  4073 
       
  4074         public Entry<K, V> firstEntry() {
       
  4075             Entry<K,V> first = nm.firstEntry();
       
  4076             return (null != first)
       
  4077                 ? new CheckedMap.CheckedEntrySet.CheckedEntry(first, valueType)
       
  4078                 : null;
       
  4079         }
       
  4080 
       
  4081         public Entry<K, V> lastEntry() {
       
  4082             Entry<K,V> last = nm.lastEntry();
       
  4083             return (null != last)
       
  4084                 ? new CheckedMap.CheckedEntrySet.CheckedEntry(last, valueType)
       
  4085                 : null;
       
  4086         }
       
  4087 
       
  4088         public Entry<K, V> pollFirstEntry() {
       
  4089             Entry<K,V> entry = nm.pollFirstEntry();
       
  4090             return (null == entry)
       
  4091                 ? null
       
  4092                 : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType);
       
  4093         }
       
  4094 
       
  4095         public Entry<K, V> pollLastEntry() {
       
  4096             Entry<K,V> entry = nm.pollLastEntry();
       
  4097             return (null == entry)
       
  4098                 ? null
       
  4099                 : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType);
       
  4100         }
       
  4101 
       
  4102         public NavigableMap<K, V> descendingMap() {
       
  4103             return checkedNavigableMap(nm.descendingMap(), keyType, valueType);
       
  4104         }
       
  4105 
       
  4106         public NavigableSet<K> keySet() {
       
  4107             return navigableKeySet();
       
  4108         }
       
  4109 
       
  4110         public NavigableSet<K> navigableKeySet() {
       
  4111             return checkedNavigableSet(nm.navigableKeySet(), keyType);
       
  4112         }
       
  4113 
       
  4114         public NavigableSet<K> descendingKeySet() {
       
  4115             return checkedNavigableSet(nm.descendingKeySet(), keyType);
       
  4116         }
       
  4117 
       
  4118         @Override
       
  4119         public NavigableMap<K,V> subMap(K fromKey, K toKey) {
       
  4120             return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false),
       
  4121                                     keyType, valueType);
       
  4122         }
       
  4123 
       
  4124         @Override
       
  4125         public NavigableMap<K,V> headMap(K toKey) {
       
  4126             return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType);
       
  4127         }
       
  4128 
       
  4129         @Override
       
  4130         public NavigableMap<K,V> tailMap(K fromKey) {
       
  4131             return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType);
       
  4132         }
       
  4133 
       
  4134         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
       
  4135             return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType);
       
  4136         }
       
  4137 
       
  4138         public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
       
  4139             return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType);
       
  4140         }
       
  4141 
       
  4142         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
       
  4143             return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType);
       
  4144         }
       
  4145     }
       
  4146 
  3410     // Empty collections
  4147     // Empty collections
  3411 
  4148 
  3412     /**
  4149     /**
  3413      * Returns an iterator that has no elements.  More precisely,
  4150      * Returns an iterator that has no elements.  More precisely,
  3414      *
  4151      *
  3426      * </ul>
  4163      * </ul>
  3427      *
  4164      *
  3428      * <p>Implementations of this method are permitted, but not
  4165      * <p>Implementations of this method are permitted, but not
  3429      * required, to return the same object from multiple invocations.
  4166      * required, to return the same object from multiple invocations.
  3430      *
  4167      *
       
  4168      * @param <T> type of elements, if there were any, in the iterator
  3431      * @return an empty iterator
  4169      * @return an empty iterator
  3432      * @since 1.7
  4170      * @since 1.7
  3433      */
  4171      */
  3434     @SuppressWarnings("unchecked")
  4172     @SuppressWarnings("unchecked")
  3435     public static <T> Iterator<T> emptyIterator() {
  4173     public static <T> Iterator<T> emptyIterator() {
  3476      * </ul>
  4214      * </ul>
  3477      *
  4215      *
  3478      * <p>Implementations of this method are permitted, but not
  4216      * <p>Implementations of this method are permitted, but not
  3479      * required, to return the same object from multiple invocations.
  4217      * required, to return the same object from multiple invocations.
  3480      *
  4218      *
       
  4219      * @param <T> type of elements, if there were any, in the iterator
  3481      * @return an empty list iterator
  4220      * @return an empty list iterator
  3482      * @since 1.7
  4221      * @since 1.7
  3483      */
  4222      */
  3484     @SuppressWarnings("unchecked")
  4223     @SuppressWarnings("unchecked")
  3485     public static <T> ListIterator<T> emptyListIterator() {
  4224     public static <T> ListIterator<T> emptyListIterator() {
  3540      */
  4279      */
  3541     @SuppressWarnings("rawtypes")
  4280     @SuppressWarnings("rawtypes")
  3542     public static final Set EMPTY_SET = new EmptySet<>();
  4281     public static final Set EMPTY_SET = new EmptySet<>();
  3543 
  4282 
  3544     /**
  4283     /**
  3545      * Returns the empty set (immutable).  This set is serializable.
  4284      * Returns an empty set (immutable).  This set is serializable.
  3546      * Unlike the like-named field, this method is parameterized.
  4285      * Unlike the like-named field, this method is parameterized.
  3547      *
  4286      *
  3548      * <p>This example illustrates the type-safe way to obtain an empty set:
  4287      * <p>This example illustrates the type-safe way to obtain an empty set:
  3549      * <pre>
  4288      * <pre>
  3550      *     Set&lt;String&gt; s = Collections.emptySet();
  4289      *     Set&lt;String&gt; s = Collections.emptySet();
  3551      * </pre>
  4290      * </pre>
  3552      * Implementation note:  Implementations of this method need not
  4291      * @implNote Implementations of this method need not create a separate
  3553      * create a separate <tt>Set</tt> object for each call.   Using this
  4292      * {@code Set} object for each call.  Using this method is likely to have
  3554      * method is likely to have comparable cost to using the like-named
  4293      * comparable cost to using the like-named field.  (Unlike this method, the
  3555      * field.  (Unlike this method, the field does not provide type safety.)
  4294      * field does not provide type safety.)
       
  4295      *
       
  4296      * @return the empty set
  3556      *
  4297      *
  3557      * @see #EMPTY_SET
  4298      * @see #EMPTY_SET
  3558      * @since 1.5
  4299      * @since 1.5
  3559      */
  4300      */
  3560     @SuppressWarnings("unchecked")
  4301     @SuppressWarnings("unchecked")
  3605             return EMPTY_SET;
  4346             return EMPTY_SET;
  3606         }
  4347         }
  3607     }
  4348     }
  3608 
  4349 
  3609     /**
  4350     /**
  3610      * Returns the empty sorted set (immutable).  This set is serializable.
  4351      * Returns an empty sorted set (immutable).  This set is serializable.
  3611      *
  4352      *
  3612      * <p>This example illustrates the type-safe way to obtain an empty sorted
  4353      * <p>This example illustrates the type-safe way to obtain an empty
  3613      * set:
  4354      * sorted set:
  3614      * <pre>
  4355      * <pre> {@code
  3615      *     SortedSet&lt;String&gt; s = Collections.emptySortedSet();
  4356      *     SortedSet<String> s = Collections.emptySortedSet();
  3616      * </pre>
  4357      * }</pre>
  3617      * Implementation note:  Implementations of this method need not
  4358      *
  3618      * create a separate <tt>SortedSet</tt> object for each call.
  4359      * @implNote Implementations of this method need not create a separate
  3619      *
  4360      * {@code SortedSet} object for each call.
       
  4361      *
       
  4362      * @param <E> type of elements, if there were any, in the set
       
  4363      * @return the empty sorted set
  3620      * @since 1.8
  4364      * @since 1.8
  3621      */
  4365      */
  3622     @SuppressWarnings("unchecked")
  4366     @SuppressWarnings("unchecked")
  3623     public static final <E> SortedSet<E> emptySortedSet() {
  4367     public static <E> SortedSet<E> emptySortedSet() {
  3624         return (SortedSet<E>) new EmptySortedSet<>();
  4368         return (SortedSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;
  3625     }
  4369     }
  3626 
  4370 
  3627     /**
  4371     /**
  3628      * @serial include
  4372      * Returns an empty navigable set (immutable).  This set is serializable.
  3629      */
  4373      *
  3630     private static class EmptySortedSet<E>
  4374      * <p>This example illustrates the type-safe way to obtain an empty
  3631         extends AbstractSet<E>
  4375      * navigable set:
  3632         implements SortedSet<E>, Serializable
  4376      * <pre> {@code
  3633     {
  4377      *     NavigableSet<String> s = Collections.emptyNavigableSet();
  3634         private static final long serialVersionUID = 6316515401502265487L;
  4378      * }</pre>
  3635         public Iterator<E> iterator() { return emptyIterator(); }
  4379      *
  3636         public int size() {return 0;}
  4380      * @implNote Implementations of this method need not
  3637         public boolean isEmpty() {return true;}
  4381      * create a separate {@code NavigableSet} object for each call.
  3638         public boolean contains(Object obj) {return false;}
  4382      *
  3639         public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
  4383      * @param <E> type of elements, if there were any, in the set
  3640         public Object[] toArray() { return new Object[0]; }
  4384      * @return the empty navigable set
  3641 
  4385      * @since 1.8
  3642         public <E> E[] toArray(E[] a) {
  4386      */
  3643             if (a.length > 0)
  4387     @SuppressWarnings("unchecked")
  3644                 a[0] = null;
  4388     public static <E> NavigableSet<E> emptyNavigableSet() {
  3645             return a;
  4389         return (NavigableSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;
  3646         }
       
  3647 
       
  3648         // Preserves singleton property
       
  3649         private Object readResolve() {
       
  3650             return new EmptySortedSet<>();
       
  3651         }
       
  3652 
       
  3653         @Override
       
  3654         public Comparator<? super E> comparator() {
       
  3655             return null;
       
  3656         }
       
  3657 
       
  3658         @Override
       
  3659         @SuppressWarnings("unchecked")
       
  3660         public SortedSet<E> subSet(Object fromElement, Object toElement) {
       
  3661             Objects.requireNonNull(fromElement);
       
  3662             Objects.requireNonNull(toElement);
       
  3663 
       
  3664             if (!(fromElement instanceof Comparable) ||
       
  3665                     !(toElement instanceof Comparable))
       
  3666             {
       
  3667                 throw new ClassCastException();
       
  3668             }
       
  3669 
       
  3670             if ((((Comparable)fromElement).compareTo(toElement) >= 0) ||
       
  3671                     (((Comparable)toElement).compareTo(fromElement) < 0))
       
  3672             {
       
  3673                 throw new IllegalArgumentException();
       
  3674             }
       
  3675 
       
  3676             return emptySortedSet();
       
  3677         }
       
  3678 
       
  3679         @Override
       
  3680         public SortedSet<E> headSet(Object toElement) {
       
  3681             Objects.requireNonNull(toElement);
       
  3682 
       
  3683             if (!(toElement instanceof Comparable)) {
       
  3684                 throw new ClassCastException();
       
  3685             }
       
  3686 
       
  3687             return emptySortedSet();
       
  3688         }
       
  3689 
       
  3690         @Override
       
  3691         public SortedSet<E> tailSet(Object fromElement) {
       
  3692             Objects.requireNonNull(fromElement);
       
  3693 
       
  3694             if (!(fromElement instanceof Comparable)) {
       
  3695                 throw new ClassCastException();
       
  3696             }
       
  3697 
       
  3698             return emptySortedSet();
       
  3699         }
       
  3700 
       
  3701         @Override
       
  3702         public E first() {
       
  3703             throw new NoSuchElementException();
       
  3704         }
       
  3705 
       
  3706         @Override
       
  3707         public E last() {
       
  3708             throw new NoSuchElementException();
       
  3709         }
       
  3710 
       
  3711         // Override default methods in Collection
       
  3712         @Override
       
  3713         public void forEach(Consumer<? super E> action) {
       
  3714             Objects.requireNonNull(action);
       
  3715         }
       
  3716 
       
  3717         @Override
       
  3718         public boolean removeIf(Predicate<? super E> filter) {
       
  3719             Objects.requireNonNull(filter);
       
  3720             return false;
       
  3721         }
       
  3722 
       
  3723         @Override
       
  3724         public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
       
  3725     }
  4390     }
  3726 
  4391 
  3727     /**
  4392     /**
  3728      * The empty list (immutable).  This list is serializable.
  4393      * The empty list (immutable).  This list is serializable.
  3729      *
  4394      *
  3731      */
  4396      */
  3732     @SuppressWarnings("rawtypes")
  4397     @SuppressWarnings("rawtypes")
  3733     public static final List EMPTY_LIST = new EmptyList<>();
  4398     public static final List EMPTY_LIST = new EmptyList<>();
  3734 
  4399 
  3735     /**
  4400     /**
  3736      * Returns the empty list (immutable).  This list is serializable.
  4401      * Returns an empty list (immutable).  This list is serializable.
  3737      *
  4402      *
  3738      * <p>This example illustrates the type-safe way to obtain an empty list:
  4403      * <p>This example illustrates the type-safe way to obtain an empty list:
  3739      * <pre>
  4404      * <pre>
  3740      *     List&lt;String&gt; s = Collections.emptyList();
  4405      *     List&lt;String&gt; s = Collections.emptyList();
  3741      * </pre>
  4406      * </pre>
  3742      * Implementation note:  Implementations of this method need not
  4407      * Implementation note:  Implementations of this method need not
  3743      * create a separate <tt>List</tt> object for each call.   Using this
  4408      * create a separate <tt>List</tt> object for each call.   Using this
  3744      * method is likely to have comparable cost to using the like-named
  4409      * method is likely to have comparable cost to using the like-named
  3745      * field.  (Unlike this method, the field does not provide type safety.)
  4410      * field.  (Unlike this method, the field does not provide type safety.)
  3746      *
  4411      *
       
  4412      * @param <T> type of elements, if there were any, in the list
       
  4413      * @return an empty immutable list
       
  4414      *
  3747      * @see #EMPTY_LIST
  4415      * @see #EMPTY_LIST
  3748      * @since 1.5
  4416      * @since 1.5
  3749      */
  4417      */
  3750     @SuppressWarnings("unchecked")
  4418     @SuppressWarnings("unchecked")
  3751     public static final <T> List<T> emptyList() {
  4419     public static final <T> List<T> emptyList() {
  3828      */
  4496      */
  3829     @SuppressWarnings("rawtypes")
  4497     @SuppressWarnings("rawtypes")
  3830     public static final Map EMPTY_MAP = new EmptyMap<>();
  4498     public static final Map EMPTY_MAP = new EmptyMap<>();
  3831 
  4499 
  3832     /**
  4500     /**
  3833      * Returns the empty map (immutable).  This map is serializable.
  4501      * Returns an empty map (immutable).  This map is serializable.
  3834      *
  4502      *
  3835      * <p>This example illustrates the type-safe way to obtain an empty set:
  4503      * <p>This example illustrates the type-safe way to obtain an empty map:
  3836      * <pre>
  4504      * <pre>
  3837      *     Map&lt;String, Date&gt; s = Collections.emptyMap();
  4505      *     Map&lt;String, Date&gt; s = Collections.emptyMap();
  3838      * </pre>
  4506      * </pre>
  3839      * Implementation note:  Implementations of this method need not
  4507      * @implNote Implementations of this method need not create a separate
  3840      * create a separate <tt>Map</tt> object for each call.   Using this
  4508      * {@code Map} object for each call.  Using this method is likely to have
  3841      * method is likely to have comparable cost to using the like-named
  4509      * comparable cost to using the like-named field.  (Unlike this method, the
  3842      * field.  (Unlike this method, the field does not provide type safety.)
  4510      * field does not provide type safety.)
  3843      *
  4511      *
       
  4512      * @return an empty map
  3844      * @see #EMPTY_MAP
  4513      * @see #EMPTY_MAP
  3845      * @since 1.5
  4514      * @since 1.5
  3846      */
  4515      */
  3847     @SuppressWarnings("unchecked")
  4516     @SuppressWarnings("unchecked")
  3848     public static final <K,V> Map<K,V> emptyMap() {
  4517     public static final <K,V> Map<K,V> emptyMap() {
  3849         return (Map<K,V>) EMPTY_MAP;
  4518         return (Map<K,V>) EMPTY_MAP;
       
  4519     }
       
  4520 
       
  4521     /**
       
  4522      * Returns an empty sorted map (immutable).  This map is serializable.
       
  4523      *
       
  4524      * <p>This example illustrates the type-safe way to obtain an empty map:
       
  4525      * <pre> {@code
       
  4526      *     SortedMap<String, Date> s = Collections.emptySortedMap();
       
  4527      * }</pre>
       
  4528      *
       
  4529      * @implNote Implementations of this method need not create a separate
       
  4530      * {@code SortedMap} object for each call.
       
  4531      *
       
  4532      * @return an empty sorted map
       
  4533      * @since 1.8
       
  4534      */
       
  4535     @SuppressWarnings("unchecked")
       
  4536     public static final <K,V> SortedMap<K,V> emptySortedMap() {
       
  4537         return (SortedMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;
       
  4538     }
       
  4539 
       
  4540     /**
       
  4541      * Returns an empty navigable map (immutable).  This map is serializable.
       
  4542      *
       
  4543      * <p>This example illustrates the type-safe way to obtain an empty map:
       
  4544      * <pre> {@code
       
  4545      *     NavigableMap<String, Date> s = Collections.emptyNavigableMap();
       
  4546      * }</pre>
       
  4547      *
       
  4548      * @implNote Implementations of this method need not create a separate
       
  4549      * {@code NavigableMap} object for each call.
       
  4550      *
       
  4551      * @return an empty navigable map
       
  4552      * @since 1.8
       
  4553      */
       
  4554     @SuppressWarnings("unchecked")
       
  4555     public static final <K,V> NavigableMap<K,V> emptyNavigableMap() {
       
  4556         return (NavigableMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;
  3850     }
  4557     }
  3851 
  4558 
  3852     /**
  4559     /**
  3853      * @serial include
  4560      * @serial include
  3854      */
  4561      */
  4151         SingletonMap(K key, V value) {
  4858         SingletonMap(K key, V value) {
  4152             k = key;
  4859             k = key;
  4153             v = value;
  4860             v = value;
  4154         }
  4861         }
  4155 
  4862 
  4156         public int size()                          {return 1;}
  4863         public int size()                                           {return 1;}
  4157 
  4864         public boolean isEmpty()                                {return false;}
  4158         public boolean isEmpty()                   {return false;}
  4865         public boolean containsKey(Object key)             {return eq(key, k);}
  4159 
  4866         public boolean containsValue(Object value)       {return eq(value, v);}
  4160         public boolean containsKey(Object key)     {return eq(key, k);}
  4867         public V get(Object key)              {return (eq(key, k) ? v : null);}
  4161 
       
  4162         public boolean containsValue(Object value) {return eq(value, v);}
       
  4163 
       
  4164         public V get(Object key)                   {return (eq(key, k) ? v : null);}
       
  4165 
  4868 
  4166         private transient Set<K> keySet = null;
  4869         private transient Set<K> keySet = null;
  4167         private transient Set<Map.Entry<K,V>> entrySet = null;
  4870         private transient Set<Map.Entry<K,V>> entrySet = null;
  4168         private transient Collection<V> values = null;
  4871         private transient Collection<V> values = null;
  4169 
  4872 
  4506         return l;
  5209         return l;
  4507     }
  5210     }
  4508 
  5211 
  4509     /**
  5212     /**
  4510      * Returns true if the specified arguments are equal, or both null.
  5213      * Returns true if the specified arguments are equal, or both null.
       
  5214      *
       
  5215      * NB: Do not replace with Object.equals until JDK-8015417 is resolved.
  4511      */
  5216      */
  4512     static boolean eq(Object o1, Object o2) {
  5217     static boolean eq(Object o1, Object o2) {
  4513         return o1==null ? o2==null : o1.equals(o2);
  5218         return o1==null ? o2==null : o1.equals(o2);
  4514     }
  5219     }
  4515 
  5220