src/share/classes/java/util/Collections.java

Print this page
rev 7019 : 7129185: Add Collections.{checked|empty|unmodifiable}Navigable{Map|Set}
Reviewed-by: duke


1195 
1196         UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1197 
1198         public Comparator<? super E> comparator() {return ss.comparator();}
1199 
1200         public SortedSet<E> subSet(E fromElement, E toElement) {
1201             return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
1202         }
1203         public SortedSet<E> headSet(E toElement) {
1204             return new UnmodifiableSortedSet<>(ss.headSet(toElement));
1205         }
1206         public SortedSet<E> tailSet(E fromElement) {
1207             return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
1208         }
1209 
1210         public E first()                   {return ss.first();}
1211         public E last()                    {return ss.last();}
1212     }
1213 
1214     /**
































































1215      * Returns an unmodifiable view of the specified list.  This method allows
1216      * modules to provide users with "read-only" access to internal
1217      * lists.  Query operations on the returned list "read through" to the
1218      * specified list, and attempts to modify the returned list, whether
1219      * direct or via its iterator, result in an
1220      * <tt>UnsupportedOperationException</tt>.<p>
1221      *
1222      * The returned list will be serializable if the specified list
1223      * is serializable. Similarly, the returned list will implement
1224      * {@link RandomAccess} if the specified list does.
1225      *
1226      * @param  list the list for which an unmodifiable view is to be returned.
1227      * @return an unmodifiable view of the specified list.
1228      */
1229     public static <T> List<T> unmodifiableList(List<? extends T> list) {
1230         return (list instanceof RandomAccess ?
1231                 new UnmodifiableRandomAccessList<>(list) :
1232                 new UnmodifiableList<>(list));
1233     }
1234 


1653         private final SortedMap<K, ? extends V> sm;
1654 
1655         UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
1656 
1657         public Comparator<? super K> comparator() {return sm.comparator();}
1658 
1659         public SortedMap<K,V> subMap(K fromKey, K toKey) {
1660             return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));
1661         }
1662         public SortedMap<K,V> headMap(K toKey) {
1663             return new UnmodifiableSortedMap<>(sm.headMap(toKey));
1664         }
1665         public SortedMap<K,V> tailMap(K fromKey) {
1666             return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));
1667         }
1668 
1669         public K firstKey()           {return sm.firstKey();}
1670         public K lastKey()            {return sm.lastKey();}
1671     }
1672 





























































































































1673 
1674     // Synch Wrappers
1675 
1676     /**
1677      * Returns a synchronized (thread-safe) collection backed by the specified
1678      * collection.  In order to guarantee serial access, it is critical that
1679      * <strong>all</strong> access to the backing collection is accomplished
1680      * through the returned collection.<p>
1681      *
1682      * It is imperative that the user manually synchronize on the returned
1683      * collection when traversing it via {@link Iterator} or
1684      * {@link Spliterator}:
1685      * <pre>
1686      *  Collection c = Collections.synchronizedCollection(myCollection);
1687      *     ...
1688      *  synchronized (c) {
1689      *      Iterator i = c.iterator(); // Must be in the synchronized block
1690      *      while (i.hasNext())
1691      *         foo(i.next());
1692      *  }


1928         public SortedSet<E> headSet(E toElement) {
1929             synchronized (mutex) {
1930                 return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
1931             }
1932         }
1933         public SortedSet<E> tailSet(E fromElement) {
1934             synchronized (mutex) {
1935                return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
1936             }
1937         }
1938 
1939         public E first() {
1940             synchronized (mutex) {return ss.first();}
1941         }
1942         public E last() {
1943             synchronized (mutex) {return ss.last();}
1944         }
1945     }
1946 
1947     /**








































































































1948      * Returns a synchronized (thread-safe) list backed by the specified
1949      * list.  In order to guarantee serial access, it is critical that
1950      * <strong>all</strong> access to the backing list is accomplished
1951      * through the returned list.<p>
1952      *
1953      * It is imperative that the user manually synchronize on the returned
1954      * list when iterating over it:
1955      * <pre>
1956      *  List list = Collections.synchronizedList(new ArrayList());
1957      *      ...
1958      *  synchronized (list) {
1959      *      Iterator i = list.iterator(); // Must be in synchronized block
1960      *      while (i.hasNext())
1961      *          foo(i.next());
1962      *  }
1963      * </pre>
1964      * Failure to follow this advice may result in non-deterministic behavior.
1965      *
1966      * <p>The returned list will be serializable if the specified list is
1967      * serializable.


2367         }
2368         public SortedMap<K,V> headMap(K toKey) {
2369             synchronized (mutex) {
2370                 return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);
2371             }
2372         }
2373         public SortedMap<K,V> tailMap(K fromKey) {
2374             synchronized (mutex) {
2375                return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);
2376             }
2377         }
2378 
2379         public K firstKey() {
2380             synchronized (mutex) {return sm.firstKey();}
2381         }
2382         public K lastKey() {
2383             synchronized (mutex) {return sm.lastKey();}
2384         }
2385     }
2386 
2387     // Dynamically typesafe collection wrappers
2388 
2389     /**
2390      * Returns a dynamically typesafe view of the specified collection.
2391      * Any attempt to insert an element of the wrong type will result in an
2392      * immediate {@link ClassCastException}.  Assuming a collection
2393      * contains no incorrectly typed elements prior to the time a
2394      * dynamically typesafe view is generated, and that all subsequent
2395      * access to the collection takes place through the view, it is
2396      * <i>guaranteed</i> that the collection cannot contain an incorrectly
2397      * typed element.
2398      *
2399      * <p>The generics mechanism in the language provides compile-time
2400      * (static) type checking, but it is possible to defeat this mechanism
2401      * with unchecked casts.  Usually this is not a problem, as the compiler
2402      * issues warnings on all such unchecked operations.  There are, however,
2403      * times when static type checking alone is not sufficient.  For example,
2404      * suppose a collection is passed to a third-party library and it is
2405      * imperative that the library code not corrupt the collection by
2406      * inserting an element of the wrong type.
2407      *
2408      * <p>Another use of dynamically typesafe views is debugging.  Suppose a
2409      * program fails with a {@code ClassCastException}, indicating that an
2410      * incorrectly typed element was put into a parameterized collection.
2411      * Unfortunately, the exception can occur at any time after the erroneous
2412      * element is inserted, so it typically provides little or no information
2413      * as to the real source of the problem.  If the problem is reproducible,
2414      * one can quickly determine its source by temporarily modifying the
2415      * program to wrap the collection with a dynamically typesafe view.
2416      * For example, this declaration:
2417      *  <pre> {@code
2418      *     Collection<String> c = new HashSet<String>();
2419      * }</pre>
2420      * may be replaced temporarily by this one:
2421      *  <pre> {@code
2422      *     Collection<String> c = Collections.checkedCollection(
2423      *         new HashSet<String>(), String.class);
2424      * }</pre>
2425      * Running the program again will cause it to fail at the point where
2426      * an incorrectly typed element is inserted into the collection, clearly
2427      * identifying the source of the problem.  Once the problem is fixed, the
2428      * modified declaration may be reverted back to the original.
2429      *
2430      * <p>The returned collection does <i>not</i> pass the hashCode and equals
2431      * operations through to the backing collection, but relies on
2432      * {@code Object}'s {@code equals} and {@code hashCode} methods.  This
2433      * is necessary to preserve the contracts of these operations in the case
2434      * that the backing collection is a set or a list.
2435      *
2436      * <p>The returned collection will be serializable if the specified
2437      * collection is serializable.



























2438      *
2439      * <p>Since {@code null} is considered to be a value of any reference
2440      * type, the returned collection permits insertion of null elements
2441      * whenever the backing collection does.
2442      *
2443      * @param c the collection for which a dynamically typesafe view is to be
2444      *          returned
2445      * @param type the type of element that {@code c} is permitted to hold
2446      * @return a dynamically typesafe view of the specified collection
2447      * @since 1.5
2448      */
2449     public static <E> Collection<E> checkedCollection(Collection<E> c,




































































































































































































2450                                                       Class<E> type) {
2451         return new CheckedCollection<>(c, type);
2452     }
2453 
2454     @SuppressWarnings("unchecked")
2455     static <T> T[] zeroLengthArray(Class<T> type) {
2456         return (T[]) Array.newInstance(type, 0);
2457     }
2458 
2459     /**
2460      * @serial include
2461      */
2462     static class CheckedCollection<E> implements Collection<E>, Serializable {
2463         private static final long serialVersionUID = 1578914078182001775L;
2464 
2465         final Collection<E> c;
2466         final Class<E> type;
2467 
2468         void typeCheck(Object o) {
2469             if (o != null && !type.isInstance(o))


2711         CheckedSortedSet(SortedSet<E> s, Class<E> type) {
2712             super(s, type);
2713             ss = s;
2714         }
2715 
2716         public Comparator<? super E> comparator() { return ss.comparator(); }
2717         public E first()                   { return ss.first(); }
2718         public E last()                    { return ss.last(); }
2719 
2720         public SortedSet<E> subSet(E fromElement, E toElement) {
2721             return checkedSortedSet(ss.subSet(fromElement,toElement), type);
2722         }
2723         public SortedSet<E> headSet(E toElement) {
2724             return checkedSortedSet(ss.headSet(toElement), type);
2725         }
2726         public SortedSet<E> tailSet(E fromElement) {
2727             return checkedSortedSet(ss.tailSet(fromElement), type);
2728         }
2729     }
2730 






































































































2731     /**
2732      * Returns a dynamically typesafe view of the specified list.
2733      * Any attempt to insert an element of the wrong type will result in
2734      * an immediate {@link ClassCastException}.  Assuming a list contains
2735      * no incorrectly typed elements prior to the time a dynamically typesafe
2736      * view is generated, and that all subsequent access to the list
2737      * takes place through the view, it is <i>guaranteed</i> that the
2738      * list cannot contain an incorrectly typed element.
2739      *
2740      * <p>A discussion of the use of dynamically typesafe views may be
2741      * found in the documentation for the {@link #checkedCollection
2742      * checkedCollection} method.
2743      *
2744      * <p>The returned list will be serializable if the specified list
2745      * is serializable.
2746      *
2747      * <p>Since {@code null} is considered to be a value of any reference
2748      * type, the returned list permits insertion of null elements whenever
2749      * the backing list does.
2750      *


3308             super(m, keyType, valueType);
3309             sm = m;
3310         }
3311 
3312         public Comparator<? super K> comparator() { return sm.comparator(); }
3313         public K firstKey()                       { return sm.firstKey(); }
3314         public K lastKey()                        { return sm.lastKey(); }
3315 
3316         public SortedMap<K,V> subMap(K fromKey, K toKey) {
3317             return checkedSortedMap(sm.subMap(fromKey, toKey),
3318                                     keyType, valueType);
3319         }
3320         public SortedMap<K,V> headMap(K toKey) {
3321             return checkedSortedMap(sm.headMap(toKey), keyType, valueType);
3322         }
3323         public SortedMap<K,V> tailMap(K fromKey) {
3324             return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);
3325         }
3326     }
3327 
3328     // Empty collections
3329 
3330     /**
3331      * Returns an iterator that has no elements.  More precisely,
3332      *
3333      * <ul compact>
3334      *
3335      * <li>{@link Iterator#hasNext hasNext} always returns {@code
3336      * false}.


3337      *
3338      * <li>{@link Iterator#next next} always throws {@link
3339      * NoSuchElementException}.



3340      *
3341      * <li>{@link Iterator#remove remove} always throws {@link
3342      * IllegalStateException}.

3343      *
3344      * </ul>

3345      *
3346      * <p>Implementations of this method are permitted, but not
3347      * required, to return the same object from multiple invocations.

3348      *
3349      * @return an empty iterator
3350      * @since 1.7




3351      */
3352     @SuppressWarnings("unchecked")
3353     public static <T> Iterator<T> emptyIterator() {
3354         return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;


























































































































































3355     }
3356 
3357     private static class EmptyIterator<E> implements Iterator<E> {
3358         static final EmptyIterator<Object> EMPTY_ITERATOR
3359             = new EmptyIterator<>();
3360 
3361         public boolean hasNext() { return false; }
3362         public E next() { throw new NoSuchElementException(); }
3363         public void remove() { throw new IllegalStateException(); }
3364         @Override
3365         public void forEachRemaining(Consumer<? super E> action) {
3366             Objects.requireNonNull(action);
3367         }
3368     }
3369 
3370     /**
3371      * Returns a list iterator that has no elements.  More precisely,
3372      *
3373      * <ul compact>
3374      *


3507 
3508         // Override default methods in Collection
3509         @Override
3510         public void forEach(Consumer<? super E> action) {
3511             Objects.requireNonNull(action);
3512         }
3513         @Override
3514         public boolean removeIf(Predicate<? super E> filter) {
3515             Objects.requireNonNull(filter);
3516             return false;
3517         }
3518         @Override
3519         public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
3520 
3521         // Preserves singleton property
3522         private Object readResolve() {
3523             return EMPTY_SET;
3524         }
3525     }
3526 



3527     /**
3528      * Returns the empty sorted set (immutable).  This set is serializable.
3529      *
3530      * <p>This example illustrates the type-safe way to obtain an empty sorted
3531      * set:
3532      * <pre>
3533      *     SortedSet&lt;String&gt; s = Collections.emptySortedSet();
3534      * </pre>
3535      * Implementation note:  Implementations of this method need not
3536      * create a separate <tt>SortedSet</tt> object for each call.




















3537      *
3538      * @since 1.8
3539      */
3540     @SuppressWarnings("unchecked")
3541     public static final <E> SortedSet<E> emptySortedSet() {
3542         return (SortedSet<E>) new EmptySortedSet<>();
3543     }
3544 
3545     /**
3546      * @serial include
3547      */
3548     private static class EmptySortedSet<E>
3549         extends AbstractSet<E>
3550         implements SortedSet<E>, Serializable
3551     {
3552         private static final long serialVersionUID = 6316515401502265487L;
3553         public Iterator<E> iterator() { return emptyIterator(); }
3554         public int size() {return 0;}
3555         public boolean isEmpty() {return true;}
3556         public boolean contains(Object obj) {return false;}
3557         public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
3558         public Object[] toArray() { return new Object[0]; }
3559 
3560         public <E> E[] toArray(E[] a) {
3561             if (a.length > 0)
3562                 a[0] = null;
3563             return a;
3564         }
3565 
3566         // Preserves singleton property
3567         private Object readResolve() {
3568             return new EmptySortedSet<>();
3569         }
3570 
3571         @Override
3572         public Comparator<? super E> comparator() {
3573             return null;
3574         }
3575 
3576         @Override
3577         @SuppressWarnings("unchecked")
3578         public SortedSet<E> subSet(Object fromElement, Object toElement) {
3579             Objects.requireNonNull(fromElement);
3580             Objects.requireNonNull(toElement);
3581 
3582             if (!(fromElement instanceof Comparable) ||
3583                     !(toElement instanceof Comparable))
3584             {
3585                 throw new ClassCastException();
3586             }
3587 
3588             if ((((Comparable)fromElement).compareTo(toElement) >= 0) ||
3589                     (((Comparable)toElement).compareTo(fromElement) < 0))
3590             {
3591                 throw new IllegalArgumentException();
3592             }
3593 
3594             return emptySortedSet();


3595         }
3596 
3597         @Override
3598         public SortedSet<E> headSet(Object toElement) {
3599             Objects.requireNonNull(toElement);

3600 
3601             if (!(toElement instanceof Comparable)) {
3602                 throw new ClassCastException();


3603             }
3604 
3605             return emptySortedSet();



3606         }
3607 
3608         @Override
3609         public SortedSet<E> tailSet(Object fromElement) {
3610             Objects.requireNonNull(fromElement);


3611 
3612             if (!(fromElement instanceof Comparable)) {
3613                 throw new ClassCastException();


3614             }
3615 
3616             return emptySortedSet();


3617         }
3618 
3619         @Override
3620         public E first() {
3621             throw new NoSuchElementException();
3622         }
3623 
3624         @Override
3625         public E last() {
3626             throw new NoSuchElementException();


























3627         }
3628 
3629         // Override default methods in Collection
3630         @Override
3631         public void forEach(Consumer<? super E> action) {
3632             Objects.requireNonNull(action);
3633         }
3634 
3635         @Override
3636         public boolean removeIf(Predicate<? super E> filter) {
3637             Objects.requireNonNull(filter);
3638             return false;
3639         }
3640 
3641         @Override
3642         public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
3643     }
3644 
3645     /**
3646      * The empty list (immutable).  This list is serializable.


3721         @Override
3722         public void sort(Comparator<? super E> c) {
3723             Objects.requireNonNull(c);
3724         }
3725 
3726         // Override default methods in Collection
3727         @Override
3728         public void forEach(Consumer<? super E> action) {
3729             Objects.requireNonNull(action);
3730         }
3731 
3732         @Override
3733         public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
3734 
3735         // Preserves singleton property
3736         private Object readResolve() {
3737             return EMPTY_LIST;
3738         }
3739     }
3740 








































































































































































































































































3741     /**
3742      * The empty map (immutable).  This map is serializable.
3743      *
3744      * @see #emptyMap()
3745      * @since 1.3
3746      */
3747     @SuppressWarnings("rawtypes")
3748     public static final Map EMPTY_MAP = new EmptyMap<>();
3749 
3750     /**
3751      * Returns the empty map (immutable).  This map is serializable.
3752      *
3753      * <p>This example illustrates the type-safe way to obtain an empty set:
3754      * <pre>
3755      *     Map&lt;String, Date&gt; s = Collections.emptyMap();
3756      * </pre>
3757      * Implementation note:  Implementations of this method need not
3758      * create a separate <tt>Map</tt> object for each call.   Using this
3759      * method is likely to have comparable cost to using the like-named
3760      * field.  (Unlike this method, the field does not provide type safety.)
3761      *
3762      * @see #EMPTY_MAP
3763      * @since 1.5
3764      */
3765     @SuppressWarnings("unchecked")
3766     public static final <K,V> Map<K,V> emptyMap() {
3767         return (Map<K,V>) EMPTY_MAP;
3768     }
3769 
3770     /**








































3771      * @serial include
3772      */
3773     private static class EmptyMap<K,V>
3774         extends AbstractMap<K,V>
3775         implements Serializable
3776     {
3777         private static final long serialVersionUID = 6428348081105594320L;
3778 
3779         public int size()                          {return 0;}
3780         public boolean isEmpty()                   {return true;}
3781         public boolean containsKey(Object key)     {return false;}
3782         public boolean containsValue(Object value) {return false;}
3783         public V get(Object key)                   {return null;}
3784         public Set<K> keySet()                     {return emptySet();}
3785         public Collection<V> values()              {return emptySet();}
3786         public Set<Map.Entry<K,V>> entrySet()      {return emptySet();}
3787 
3788         public boolean equals(Object o) {
3789             return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
3790         }


3838         public V computeIfPresent(K key,
3839                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
3840             throw new UnsupportedOperationException();
3841         }
3842 
3843         @Override
3844         public V compute(K key,
3845                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
3846             throw new UnsupportedOperationException();
3847         }
3848 
3849         @Override
3850         public V merge(K key, V value,
3851                 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
3852             throw new UnsupportedOperationException();
3853         }
3854 
3855         // Preserves singleton property
3856         private Object readResolve() {
3857             return EMPTY_MAP;





































































































































3858         }
3859     }
3860 
3861     // Singleton collections
3862 
3863     /**
3864      * Returns an immutable set containing only the specified object.
3865      * The returned set is serializable.
3866      *
3867      * @param o the sole object to be stored in the returned set.
3868      * @return an immutable set containing only the specified object.
3869      */
3870     public static <T> Set<T> singleton(T o) {
3871         return new SingletonSet<>(o);
3872     }
3873 
3874     static <E> Iterator<E> singletonIterator(final E e) {
3875         return new Iterator<E>() {
3876             private boolean hasNext = true;
3877             public boolean hasNext() {




1195 
1196         UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1197 
1198         public Comparator<? super E> comparator() {return ss.comparator();}
1199 
1200         public SortedSet<E> subSet(E fromElement, E toElement) {
1201             return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
1202         }
1203         public SortedSet<E> headSet(E toElement) {
1204             return new UnmodifiableSortedSet<>(ss.headSet(toElement));
1205         }
1206         public SortedSet<E> tailSet(E fromElement) {
1207             return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
1208         }
1209 
1210         public E first()                   {return ss.first();}
1211         public E last()                    {return ss.last();}
1212     }
1213 
1214     /**
1215      * Returns an unmodifiable view of the specified navigable set.  This method
1216      * allows modules to provide users with "read-only" access to internal
1217      * navigable sets.  Query operations on the returned navigable set "read
1218      * through" to the specified navigable set.  Attempts to modify the returned
1219      * navigable set, whether direct, via its iterator, or via its
1220      * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in
1221      * an <tt>UnsupportedOperationException</tt>.<p>
1222      *
1223      * The returned navigable set will be serializable if the specified sorted set
1224      * is serializable.
1225      *
1226      * @param s the navigable set for which an unmodifiable view is to be
1227      *        returned
1228      * @return an unmodifiable view of the specified navigable set
1229      * @since 1.8
1230      */
1231     public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) {
1232         return new UnmodifiableNavigableSet<>(s);
1233     }
1234 
1235     /**
1236      * @serial include
1237      */
1238     static class UnmodifiableNavigableSet<E>
1239                              extends UnmodifiableSortedSet<E>
1240                              implements NavigableSet<E>, Serializable {
1241 
1242         private final NavigableSet<E> ns;
1243 
1244         UnmodifiableNavigableSet(NavigableSet<E> s) {super(s); ns = s;}
1245 
1246         @Override public E lower(E e) { return ns.lower(e); }
1247         @Override public E floor(E e) { return ns.floor(e); }
1248         @Override public E ceiling(E e) { return ns.ceiling(e); }
1249         @Override public E higher(E e) { return ns.higher(e); }
1250         @Override public E pollFirst() { throw new UnsupportedOperationException(); }
1251         @Override public E pollLast() { throw new UnsupportedOperationException(); }
1252         @Override
1253         public NavigableSet<E> descendingSet() {
1254             return new UnmodifiableNavigableSet<>(ns.descendingSet());
1255         }
1256 
1257         @Override
1258         public Iterator<E> descendingIterator() {
1259             return descendingSet().iterator();
1260         }
1261 
1262         @Override
1263         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
1264             return new UnmodifiableNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive));
1265         }
1266 
1267         @Override
1268         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1269             return new UnmodifiableNavigableSet<>(ns.headSet(toElement, inclusive));
1270         }
1271 
1272         @Override
1273         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1274             return new UnmodifiableNavigableSet<>(ns.tailSet(fromElement, inclusive));
1275         }
1276     }
1277 
1278     /**
1279      * Returns an unmodifiable view of the specified list.  This method allows
1280      * modules to provide users with "read-only" access to internal
1281      * lists.  Query operations on the returned list "read through" to the
1282      * specified list, and attempts to modify the returned list, whether
1283      * direct or via its iterator, result in an
1284      * <tt>UnsupportedOperationException</tt>.<p>
1285      *
1286      * The returned list will be serializable if the specified list
1287      * is serializable. Similarly, the returned list will implement
1288      * {@link RandomAccess} if the specified list does.
1289      *
1290      * @param  list the list for which an unmodifiable view is to be returned.
1291      * @return an unmodifiable view of the specified list.
1292      */
1293     public static <T> List<T> unmodifiableList(List<? extends T> list) {
1294         return (list instanceof RandomAccess ?
1295                 new UnmodifiableRandomAccessList<>(list) :
1296                 new UnmodifiableList<>(list));
1297     }
1298 


1717         private final SortedMap<K, ? extends V> sm;
1718 
1719         UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
1720 
1721         public Comparator<? super K> comparator() {return sm.comparator();}
1722 
1723         public SortedMap<K,V> subMap(K fromKey, K toKey) {
1724             return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));
1725         }
1726         public SortedMap<K,V> headMap(K toKey) {
1727             return new UnmodifiableSortedMap<>(sm.headMap(toKey));
1728         }
1729         public SortedMap<K,V> tailMap(K fromKey) {
1730             return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));
1731         }
1732 
1733         public K firstKey()           {return sm.firstKey();}
1734         public K lastKey()            {return sm.lastKey();}
1735     }
1736 
1737     /**
1738      * Returns an unmodifiable view of the specified navigable map.  This method
1739      * allows modules to provide users with "read-only" access to internal
1740      * navigable maps.  Query operations on the returned navigable map "read
1741      * through" to the specified navigable map.  Attempts to modify the returned
1742      * navigable map, whether direct, via its collection views, or via its
1743      * <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in
1744      * an <tt>UnsupportedOperationException</tt>.<p>
1745      *
1746      * The returned navigable map will be serializable if the specified
1747      * navigable map is serializable.
1748      *
1749      * @param m the navigable map for which an unmodifiable view is to be
1750      *        returned
1751      * @return an unmodifiable view of the specified navigable map
1752      * @since 1.8
1753      */
1754     public static <K,V> SortedMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {
1755         return new UnmodifiableNavigableMap<>(m);
1756     }
1757 
1758     /**
1759      * @serial include
1760      */
1761     static class UnmodifiableNavigableMap<K,V>
1762           extends UnmodifiableSortedMap<K,V>
1763           implements NavigableMap<K,V>, Serializable {
1764         // private static final long serialVersionUID = -8806743815996713206L;
1765 
1766         private final NavigableMap<K, ? extends V> nm;
1767 
1768         UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {super(m); nm = m;}
1769 
1770         @Override
1771         public Entry<K, V> lowerEntry(K key) {
1772             return new UnmodifiableEntrySet.UnmodifiableEntry(nm.lowerEntry(key));
1773         }
1774 
1775         @Override
1776         public K lowerKey(K key) {
1777             return nm.lowerKey(key);
1778         }
1779 
1780         @Override
1781         public Entry<K, V> floorEntry(K key) {
1782             return new UnmodifiableEntrySet.UnmodifiableEntry(nm.floorEntry(key));
1783         }
1784 
1785         @Override
1786         public K floorKey(K key) {
1787             return nm.floorKey(key);
1788         }
1789 
1790         @Override
1791         public Entry<K, V> ceilingEntry(K key) {
1792             return new UnmodifiableEntrySet.UnmodifiableEntry(nm.ceilingEntry(key));
1793         }
1794 
1795         @Override
1796         public K ceilingKey(K key) {
1797             return nm.ceilingKey(key);
1798         }
1799 
1800         @Override
1801         public Entry<K, V> higherEntry(K key) {
1802             return new UnmodifiableEntrySet.UnmodifiableEntry(nm.higherEntry(key));
1803         }
1804 
1805         @Override
1806         public K higherKey(K key) {
1807             return nm.higherKey(key);
1808         }
1809 
1810         @Override
1811         public Entry<K, V> firstEntry() {
1812             return new UnmodifiableEntrySet.UnmodifiableEntry(nm.firstEntry());
1813         }
1814 
1815         @Override
1816         public Entry<K, V> lastEntry() {
1817             return new UnmodifiableEntrySet.UnmodifiableEntry(nm.lastEntry());
1818         }
1819 
1820         @Override
1821         public Entry<K, V> pollFirstEntry() {
1822             Entry<K,V> entry = (Entry<K,V>) nm.pollFirstEntry();
1823             return (null == entry) ? null : new UnmodifiableEntrySet.UnmodifiableEntry(entry);
1824         }
1825 
1826         @Override
1827         public Entry<K, V> pollLastEntry() {
1828             Entry<K,V> entry = (Entry<K,V>) nm.pollLastEntry();
1829             return (null == entry) ? null : new UnmodifiableEntrySet.UnmodifiableEntry(entry);
1830         }
1831 
1832         @Override
1833         public NavigableMap<K, V> descendingMap() {
1834             return (NavigableMap<K,V>) unmodifiableNavigableMap(nm.descendingMap());
1835         }
1836 
1837         @Override
1838         public NavigableSet<K> navigableKeySet() {
1839             return unmodifiableNavigableSet(nm.navigableKeySet());
1840         }
1841 
1842         @Override
1843         public NavigableSet<K> descendingKeySet() {
1844             return unmodifiableNavigableSet(nm.descendingKeySet());
1845         }
1846 
1847         @Override
1848         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
1849             return (NavigableMap<K,V>) unmodifiableNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive));
1850         }
1851 
1852         @Override
1853         public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
1854             return (NavigableMap<K,V>) unmodifiableNavigableMap(nm.headMap(toKey, inclusive));
1855         }
1856 
1857         @Override
1858         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
1859             return (NavigableMap<K,V>) unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive));
1860         }
1861     }
1862 
1863     // Synch Wrappers
1864 
1865     /**
1866      * Returns a synchronized (thread-safe) collection backed by the specified
1867      * collection.  In order to guarantee serial access, it is critical that
1868      * <strong>all</strong> access to the backing collection is accomplished
1869      * through the returned collection.<p>
1870      *
1871      * It is imperative that the user manually synchronize on the returned
1872      * collection when traversing it via {@link Iterator} or
1873      * {@link Spliterator}:
1874      * <pre>
1875      *  Collection c = Collections.synchronizedCollection(myCollection);
1876      *     ...
1877      *  synchronized (c) {
1878      *      Iterator i = c.iterator(); // Must be in the synchronized block
1879      *      while (i.hasNext())
1880      *         foo(i.next());
1881      *  }


2117         public SortedSet<E> headSet(E toElement) {
2118             synchronized (mutex) {
2119                 return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
2120             }
2121         }
2122         public SortedSet<E> tailSet(E fromElement) {
2123             synchronized (mutex) {
2124                return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
2125             }
2126         }
2127 
2128         public E first() {
2129             synchronized (mutex) {return ss.first();}
2130         }
2131         public E last() {
2132             synchronized (mutex) {return ss.last();}
2133         }
2134     }
2135 
2136     /**
2137      * Returns a synchronized (thread-safe) sorted set backed by the specified
2138      * navigable set.  In order to guarantee serial access, it is critical that
2139      * <strong>all</strong> access to the backing sorted set is accomplished
2140      * through the returned navigable set (or its views).<p>
2141      *
2142      * It is imperative that the user manually synchronize on the returned
2143      * navigable set when iterating over it or any of its <tt>subSet</tt>,
2144      * <tt>headSet</tt>, or <tt>tailSet</tt> views.
2145      * <pre>
2146      *  SortedSet s = Collections.synchronizedNavigableSet(new TreeSet());
2147      *      ...
2148      *  synchronized (s) {
2149      *      Iterator i = s.iterator(); // Must be in the synchronized block
2150      *      while (i.hasNext())
2151      *          foo(i.next());
2152      *  }
2153      * </pre>
2154      * or:
2155      * <pre>
2156      *  SortedSet s = Collections.synchronizedNavigableSet(new TreeSet());
2157      *  SortedSet s2 = s.headSet(foo);
2158      *      ...
2159      *  synchronized (s) {  // Note: s, not s2!!!
2160      *      Iterator i = s2.iterator(); // Must be in the synchronized block
2161      *      while (i.hasNext())
2162      *          foo(i.next());
2163      *  }
2164      * </pre>
2165      * Failure to follow this advice may result in non-deterministic behavior.
2166      *
2167      * <p>The returned navigable set will be serializable if the specified
2168      * navigable set is serializable.
2169      *
2170      * @param  s the navigable set to be "wrapped" in a synchronized navigable
2171      * set
2172      * @return a synchronized view of the specified navigable set
2173      * @since 1.8
2174      */
2175     public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) {
2176         return new SynchronizedNavigableSet<>(s);
2177     }
2178 
2179     /**
2180      * @serial include
2181      */
2182     static class SynchronizedNavigableSet<E>
2183         extends SynchronizedSortedSet<E>
2184         implements NavigableSet<E>
2185     {
2186         //private static final long serialVersionUID = 8695801310862127406L;
2187 
2188         private final NavigableSet<E> ns;
2189 
2190         SynchronizedNavigableSet(NavigableSet<E> s) {
2191             super(s);
2192             ns = s;
2193         }
2194         SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) {
2195             super(s, mutex);
2196             ns = s;
2197         }
2198         @Override public E lower(E e) { synchronized (mutex) {return ns.lower(e);} }
2199         @Override public E floor(E e) { synchronized (mutex) {return ns.floor(e);} }
2200         @Override public E ceiling(E e) { synchronized (mutex) {return ns.ceiling(e);} }
2201         @Override public E higher(E e) { synchronized (mutex) {return ns.higher(e);} }
2202         @Override public E pollFirst() { synchronized (mutex) {return ns.pollFirst();} }
2203         @Override public E pollLast() { synchronized (mutex) {return ns.pollLast();}  }
2204         @Override
2205         public NavigableSet<E> descendingSet() {
2206             synchronized (mutex) {
2207             return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex);
2208             }
2209         }
2210 
2211         @Override
2212         public Iterator<E> descendingIterator() {
2213             synchronized (mutex) {
2214             return descendingSet().iterator();
2215             }
2216         }
2217 
2218         @Override
2219         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
2220             synchronized (mutex) {
2221             return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex);
2222             }
2223         }
2224 
2225         @Override
2226         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
2227             synchronized (mutex) {
2228             return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex);
2229             }
2230         }
2231 
2232         @Override
2233         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
2234             synchronized (mutex) {
2235             return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive));
2236             }
2237         }
2238     }
2239 
2240     /**
2241      * Returns a synchronized (thread-safe) list backed by the specified
2242      * list.  In order to guarantee serial access, it is critical that
2243      * <strong>all</strong> access to the backing list is accomplished
2244      * through the returned list.<p>
2245      *
2246      * It is imperative that the user manually synchronize on the returned
2247      * list when iterating over it:
2248      * <pre>
2249      *  List list = Collections.synchronizedList(new ArrayList());
2250      *      ...
2251      *  synchronized (list) {
2252      *      Iterator i = list.iterator(); // Must be in synchronized block
2253      *      while (i.hasNext())
2254      *          foo(i.next());
2255      *  }
2256      * </pre>
2257      * Failure to follow this advice may result in non-deterministic behavior.
2258      *
2259      * <p>The returned list will be serializable if the specified list is
2260      * serializable.


2660         }
2661         public SortedMap<K,V> headMap(K toKey) {
2662             synchronized (mutex) {
2663                 return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);
2664             }
2665         }
2666         public SortedMap<K,V> tailMap(K fromKey) {
2667             synchronized (mutex) {
2668                return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);
2669             }
2670         }
2671 
2672         public K firstKey() {
2673             synchronized (mutex) {return sm.firstKey();}
2674         }
2675         public K lastKey() {
2676             synchronized (mutex) {return sm.lastKey();}
2677         }
2678     }
2679 


2680     /**
2681      * Returns a synchronized (thread-safe) navigable map backed by the
2682      * specified navigable map.  In order to guarantee serial access, it is
2683      * critical that <strong>all</strong> access to the backing navigable map is
2684      * accomplished through the returned navigable map (or its views).<p>









































2685      *
2686      * It is imperative that the user manually synchronize on the returned
2687      * navigable map when iterating over any of its collection views, or the
2688      * collections views of any of its <tt>subMap</tt>, <tt>headMap</tt> or
2689      * <tt>tailMap</tt> views.
2690      * <pre>
2691      *  SortedMap m = Collections.synchronizedNavigableMap(new TreeMap());
2692      *      ...
2693      *  Set s = m.keySet();  // Needn't be in synchronized block
2694      *      ...
2695      *  synchronized (m) {  // Synchronizing on m, not s!
2696      *      Iterator i = s.iterator(); // Must be in synchronized block
2697      *      while (i.hasNext())
2698      *          foo(i.next());
2699      *  }
2700      * </pre>
2701      * or:
2702      * <pre>
2703      *  SortedMap m = Collections.synchronizedNavigableMap(new TreeMap());
2704      *  SortedMap m2 = m.subMap(foo, bar);
2705      *      ...
2706      *  Set s2 = m2.keySet();  // Needn't be in synchronized block
2707      *      ...
2708      *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
2709      *      Iterator i = s.iterator(); // Must be in synchronized block
2710      *      while (i.hasNext())
2711      *          foo(i.next());
2712      *  }
2713      * </pre>
2714      * Failure to follow this advice may result in non-deterministic behavior.
2715      *
2716      * <p>The returned navigable map will be serializable if the specified
2717      * navigable map is serializable.

2718      *
2719      * @param  m the navigable map to be "wrapped" in a synchronized navigable
2720      *              map
2721      * @return a synchronized view of the specified navigable map.
2722      * @since 1.8

2723      */
2724     public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) {
2725         return new SynchronizedNavigableMap<>(m);
2726     }
2727 
2728 
2729     /**
2730      * @serial include
2731      */
2732     static class SynchronizedNavigableMap<K,V>
2733         extends SynchronizedSortedMap<K,V>
2734         implements NavigableMap<K,V>
2735     {
2736         private static final long serialVersionUID = -8798146769416483793L;
2737 
2738         private final NavigableMap<K,V> nm;
2739 
2740         SynchronizedNavigableMap(NavigableMap<K,V> m) {
2741             super(m);
2742             nm = m;
2743         }
2744         SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) {
2745             super(m, mutex);
2746             nm = m;
2747         }
2748 
2749         @Override
2750         public Entry<K, V> lowerEntry(K key) {
2751             synchronized (mutex) { return nm.lowerEntry(key); }
2752         }
2753 
2754         @Override
2755         public K lowerKey(K key) {
2756             synchronized (mutex) { return nm.lowerKey(key); }
2757         }
2758 
2759         @Override
2760         public Entry<K, V> floorEntry(K key) {
2761             synchronized (mutex) { return nm.floorEntry(key); }
2762         }
2763 
2764         @Override
2765         public K floorKey(K key) {
2766             synchronized (mutex) { return nm.floorKey(key); }
2767         }
2768 
2769         @Override
2770         public Entry<K, V> ceilingEntry(K key) {
2771             synchronized (mutex) { return nm.ceilingEntry(key); }
2772         }
2773 
2774         @Override
2775         public K ceilingKey(K key) {
2776             synchronized (mutex) { return nm.ceilingKey(key); }
2777         }
2778 
2779         @Override
2780         public Entry<K, V> higherEntry(K key) {
2781             synchronized (mutex) { return nm.higherEntry(key); }
2782         }
2783 
2784         @Override
2785         public K higherKey(K key) {
2786             synchronized (mutex) { return nm.higherKey(key); }
2787         }
2788 
2789         @Override
2790         public Entry<K, V> firstEntry() {
2791             synchronized (mutex) { return nm.firstEntry(); }
2792         }
2793 
2794         @Override
2795         public Entry<K, V> lastEntry() {
2796             synchronized (mutex) { return nm.lastEntry(); }
2797         }
2798 
2799         @Override
2800         public Entry<K, V> pollFirstEntry() {
2801             synchronized (mutex) {
2802             Entry<K,V> entry = (Entry<K,V>) nm.pollFirstEntry();
2803             return (null == entry) ? null : entry;
2804             }
2805         }
2806 
2807         @Override
2808         public Entry<K, V> pollLastEntry() {
2809             synchronized (mutex) {
2810             Entry<K,V> entry = (Entry<K,V>) nm.pollLastEntry();
2811             return (null == entry) ? null : entry;
2812             }
2813         }
2814 
2815         @Override
2816         public NavigableMap<K, V> descendingMap() {
2817             synchronized (mutex) {
2818             return (NavigableMap<K,V>) new SynchronizedNavigableMap(nm.descendingMap(), mutex);
2819             }
2820         }
2821 
2822         @Override
2823         public NavigableSet<K> navigableKeySet() {
2824             synchronized (mutex) {
2825                 return new SynchronizedNavigableSet(nm.navigableKeySet(), mutex);
2826             }
2827         }
2828 
2829         @Override
2830         public NavigableSet<K> descendingKeySet() {
2831             synchronized (mutex) {
2832                 return new SynchronizedNavigableSet(nm.descendingKeySet(), mutex);
2833             }
2834         }
2835 
2836         @Override
2837         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
2838             synchronized (mutex) {
2839                 return (NavigableMap<K,V>) new SynchronizedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex);
2840             }
2841         }
2842 
2843         @Override
2844         public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
2845             synchronized (mutex) {
2846                 return (NavigableMap<K,V>) new SynchronizedNavigableMap(nm.headMap(toKey, inclusive), mutex);
2847             }
2848         }
2849 
2850         @Override
2851         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
2852             synchronized (mutex) {
2853                 return (NavigableMap<K,V>) new SynchronizedNavigableMap(nm.tailMap(fromKey, inclusive), mutex);
2854             }
2855         }
2856     }
2857 
2858     // Dynamically typesafe collection wrappers
2859 
2860     /**
2861      * Returns a dynamically typesafe view of the specified collection.
2862      * Any attempt to insert an element of the wrong type will result in an
2863      * immediate {@link ClassCastException}.  Assuming a collection
2864      * contains no incorrectly typed elements prior to the time a
2865      * dynamically typesafe view is generated, and that all subsequent
2866      * access to the collection takes place through the view, it is
2867      * <i>guaranteed</i> that the collection cannot contain an incorrectly
2868      * typed element.
2869      *
2870      * <p>The generics mechanism in the language provides compile-time
2871      * (static) type checking, but it is possible to defeat this mechanism
2872      * with unchecked casts.  Usually this is not a problem, as the compiler
2873      * issues warnings on all such unchecked operations.  There are, however,
2874      * times when static type checking alone is not sufficient.  For example,
2875      * suppose a collection is passed to a third-party library and it is
2876      * imperative that the library code not corrupt the collection by
2877      * inserting an element of the wrong type.
2878      *
2879      * <p>Another use of dynamically typesafe views is debugging.  Suppose a
2880      * program fails with a {@code ClassCastException}, indicating that an
2881      * incorrectly typed element was put into a parameterized collection.
2882      * Unfortunately, the exception can occur at any time after the erroneous
2883      * element is inserted, so it typically provides little or no information
2884      * as to the real source of the problem.  If the problem is reproducible,
2885      * one can quickly determine its source by temporarily modifying the
2886      * program to wrap the collection with a dynamically typesafe view.
2887      * For example, this declaration:
2888      *  <pre> {@code
2889      *     Collection<String> c = new HashSet<String>();
2890      * }</pre>
2891      * may be replaced temporarily by this one:
2892      *  <pre> {@code
2893      *     Collection<String> c = Collections.checkedCollection(
2894      *         new HashSet<String>(), String.class);
2895      * }</pre>
2896      * Running the program again will cause it to fail at the point where
2897      * an incorrectly typed element is inserted into the collection, clearly
2898      * identifying the source of the problem.  Once the problem is fixed, the
2899      * modified declaration may be reverted back to the original.
2900      *
2901      * <p>The returned collection does <i>not</i> pass the hashCode and equals
2902      * operations through to the backing collection, but relies on
2903      * {@code Object}'s {@code equals} and {@code hashCode} methods.  This
2904      * is necessary to preserve the contracts of these operations in the case
2905      * that the backing collection is a set or a list.
2906      *
2907      * <p>The returned collection will be serializable if the specified
2908      * collection is serializable.
2909      *
2910      * <p>Since {@code null} is considered to be a value of any reference
2911      * type, the returned collection permits insertion of null elements
2912      * whenever the backing collection does.
2913      *
2914      * @param c the collection for which a dynamically typesafe view is to be
2915      *          returned
2916      * @param type the type of element that {@code c} is permitted to hold
2917      * @return a dynamically typesafe view of the specified collection
2918      * @since 1.5
2919      */
2920     public static <E> Collection<E> checkedCollection(Collection<E> c,
2921                                                       Class<E> type) {
2922         return new CheckedCollection<>(c, type);
2923     }
2924 
2925     @SuppressWarnings("unchecked")
2926     static <T> T[] zeroLengthArray(Class<T> type) {
2927         return (T[]) Array.newInstance(type, 0);
2928     }
2929 
2930     /**
2931      * @serial include
2932      */
2933     static class CheckedCollection<E> implements Collection<E>, Serializable {
2934         private static final long serialVersionUID = 1578914078182001775L;
2935 
2936         final Collection<E> c;
2937         final Class<E> type;
2938 
2939         void typeCheck(Object o) {
2940             if (o != null && !type.isInstance(o))


3182         CheckedSortedSet(SortedSet<E> s, Class<E> type) {
3183             super(s, type);
3184             ss = s;
3185         }
3186 
3187         public Comparator<? super E> comparator() { return ss.comparator(); }
3188         public E first()                   { return ss.first(); }
3189         public E last()                    { return ss.last(); }
3190 
3191         public SortedSet<E> subSet(E fromElement, E toElement) {
3192             return checkedSortedSet(ss.subSet(fromElement,toElement), type);
3193         }
3194         public SortedSet<E> headSet(E toElement) {
3195             return checkedSortedSet(ss.headSet(toElement), type);
3196         }
3197         public SortedSet<E> tailSet(E fromElement) {
3198             return checkedSortedSet(ss.tailSet(fromElement), type);
3199         }
3200     }
3201 
3202 /**
3203      * Returns a dynamically typesafe view of the specified navigable set.
3204      * Any attempt to insert an element of the wrong type will result in an
3205      * immediate {@link ClassCastException}.  Assuming a navigable set
3206      * contains no incorrectly typed elements prior to the time a
3207      * dynamically typesafe view is generated, and that all subsequent
3208      * access to the navigable set takes place through the view, it is
3209      * <em>guaranteed</em> that the navigable set cannot contain an incorrectly
3210      * typed element.
3211      *
3212      * <p>A discussion of the use of dynamically typesafe views may be
3213      * found in the documentation for the {@link #checkedCollection
3214      * checkedCollection} method.
3215      *
3216      * <p>The returned navigable set will be serializable if the specified
3217      * navigable set is serializable.
3218      *
3219      * <p>Since {@code null} is considered to be a value of any reference
3220      * type, the returned navigable set permits insertion of null elements
3221      * whenever the backing sorted set does.
3222      *
3223      * @param s the navigable set for which a dynamically typesafe view is to be
3224      *          returned
3225      * @param type the type of element that {@code s} is permitted to hold
3226      * @return a dynamically typesafe view of the specified navigable set
3227      * @since 1.8
3228      */
3229     public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,
3230                                                     Class<E> type) {
3231         return new CheckedNavigableSet<>(s, type);
3232     }
3233 
3234     /**
3235      * @serial include
3236      */
3237     static class CheckedNavigableSet<E> extends CheckedSortedSet<E>
3238         implements NavigableSet<E>, Serializable
3239     {
3240         //private static final long serialVersionUID = 1599911165492914959L;
3241         private final NavigableSet<E> ns;
3242 
3243         CheckedNavigableSet(NavigableSet<E> s, Class<E> type) {
3244             super(s, type);
3245             ns = s;
3246         }
3247 
3248         @Override
3249         public E lower(E e) {
3250             return ns.lower(e);
3251         }
3252 
3253         @Override
3254         public E floor(E e) {
3255             return ns.floor(e);
3256         }
3257 
3258         @Override
3259         public E ceiling(E e) {
3260             return ns.ceiling(e);
3261         }
3262 
3263         @Override
3264         public E higher(E e) {
3265             return ns.higher(e);
3266         }
3267 
3268         @Override
3269         public E pollFirst() {
3270             return ns.pollFirst();
3271         }
3272 
3273         @Override
3274         public E pollLast() {
3275             return ns.pollLast();
3276         }
3277 
3278         @Override
3279         public NavigableSet<E> descendingSet() {
3280             return checkedNavigableSet(ns.descendingSet(), type);
3281         }
3282 
3283         @Override
3284         public Iterator<E> descendingIterator() {
3285             return checkedNavigableSet(ns.descendingSet(), type).iterator();
3286         }
3287 
3288         @Override
3289         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
3290             return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type);
3291         }
3292 
3293         @Override
3294         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
3295             return checkedNavigableSet(ns.headSet(toElement, inclusive), type);
3296         }
3297 
3298         @Override
3299         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
3300             return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type);
3301         }
3302     }
3303 
3304     /**
3305      * Returns a dynamically typesafe view of the specified list.
3306      * Any attempt to insert an element of the wrong type will result in
3307      * an immediate {@link ClassCastException}.  Assuming a list contains
3308      * no incorrectly typed elements prior to the time a dynamically typesafe
3309      * view is generated, and that all subsequent access to the list
3310      * takes place through the view, it is <i>guaranteed</i> that the
3311      * list cannot contain an incorrectly typed element.
3312      *
3313      * <p>A discussion of the use of dynamically typesafe views may be
3314      * found in the documentation for the {@link #checkedCollection
3315      * checkedCollection} method.
3316      *
3317      * <p>The returned list will be serializable if the specified list
3318      * is serializable.
3319      *
3320      * <p>Since {@code null} is considered to be a value of any reference
3321      * type, the returned list permits insertion of null elements whenever
3322      * the backing list does.
3323      *


3881             super(m, keyType, valueType);
3882             sm = m;
3883         }
3884 
3885         public Comparator<? super K> comparator() { return sm.comparator(); }
3886         public K firstKey()                       { return sm.firstKey(); }
3887         public K lastKey()                        { return sm.lastKey(); }
3888 
3889         public SortedMap<K,V> subMap(K fromKey, K toKey) {
3890             return checkedSortedMap(sm.subMap(fromKey, toKey),
3891                                     keyType, valueType);
3892         }
3893         public SortedMap<K,V> headMap(K toKey) {
3894             return checkedSortedMap(sm.headMap(toKey), keyType, valueType);
3895         }
3896         public SortedMap<K,V> tailMap(K fromKey) {
3897             return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);
3898         }
3899     }
3900 


3901     /**
3902      * Returns a dynamically typesafe view of the specified navigable map.
3903      * Any attempt to insert a mapping whose key or value have the wrong
3904      * type will result in an immediate {@link ClassCastException}.
3905      * Similarly, any attempt to modify the value currently associated with
3906      * a key will result in an immediate {@link ClassCastException},
3907      * whether the modification is attempted directly through the map
3908      * itself, or through a {@link Map.Entry} instance obtained from the
3909      * map's {@link Map#entrySet() entry set} view.
3910      *
3911      * <p>Assuming a map contains no incorrectly typed keys or values
3912      * prior to the time a dynamically typesafe view is generated, and
3913      * that all subsequent access to the map takes place through the view
3914      * (or one of its collection views), it is <em>guaranteed</em> that the
3915      * map cannot contain an incorrectly typed key or value.
3916      *
3917      * <p>A discussion of the use of dynamically typesafe views may be
3918      * found in the documentation for the {@link #checkedCollection
3919      * checkedCollection} method.
3920      *
3921      * <p>The returned map will be serializable if the specified map is
3922      * serializable.
3923      *
3924      * <p>Since {@code null} is considered to be a value of any reference
3925      * type, the returned map permits insertion of null keys or values
3926      * whenever the backing map does.
3927      *
3928      * @param m the map for which a dynamically typesafe view is to be
3929      *          returned
3930      * @param keyType the type of key that {@code m} is permitted to hold
3931      * @param valueType the type of value that {@code m} is permitted to hold
3932      * @return a dynamically typesafe view of the specified map
3933      * @since 1.8
3934      */
3935     public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m,
3936                                                         Class<K> keyType,
3937                                                         Class<V> valueType) {
3938         return new CheckedNavigableMap<>(m, keyType, valueType);
3939     }
3940 
3941     /**
3942      * @serial include
3943      */
3944     static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V>
3945         implements NavigableMap<K,V>, Serializable
3946     {
3947         //private static final long serialVersionUID = 1599671320688067438L;
3948 
3949         private final NavigableMap<K, V> nm;
3950 
3951         CheckedNavigableMap(NavigableMap<K, V> m,
3952                          Class<K> keyType, Class<V> valueType) {
3953             super(m, keyType, valueType);
3954             nm = m;
3955         }
3956 
3957         public Comparator<? super K> comparator() { return nm.comparator(); }
3958         public K firstKey()                       { return nm.firstKey(); }
3959         public K lastKey()                        { return nm.lastKey(); }
3960 
3961         public NavigableMap<K,V> subMap(K fromKey, K toKey) {
3962             return checkedNavigableMap((NavigableMap<K,V>)nm.subMap(fromKey, toKey),
3963                                     keyType, valueType);
3964         }
3965         public NavigableMap<K,V> headMap(K toKey) {
3966             return checkedNavigableMap((NavigableMap<K,V>)nm.headMap(toKey), keyType, valueType);
3967         }
3968         public NavigableMap<K,V> tailMap(K fromKey) {
3969             return checkedNavigableMap((NavigableMap<K,V>)nm.tailMap(fromKey), keyType, valueType);
3970         }
3971 
3972         @Override
3973         public Entry<K, V> lowerEntry(K key) {
3974             return new CheckedMap.CheckedEntrySet.CheckedEntry(nm.lowerEntry(key), valueType);
3975         }
3976 
3977         @Override
3978         public K lowerKey(K key) {
3979             return nm.lowerKey(key);
3980         }
3981 
3982         @Override
3983         public Entry<K, V> floorEntry(K key) {
3984             return new CheckedMap.CheckedEntrySet.CheckedEntry(nm.lowerEntry(key), valueType);
3985         }
3986 
3987         @Override
3988         public K floorKey(K key) {
3989             return nm.floorKey(key);
3990         }
3991 
3992         @Override
3993         public Entry<K, V> ceilingEntry(K key) {
3994             return new CheckedMap.CheckedEntrySet.CheckedEntry(nm.ceilingEntry(key), valueType);
3995         }
3996 
3997         @Override
3998         public K ceilingKey(K key) {
3999             return nm.ceilingKey(key);
4000         }
4001 
4002         @Override
4003         public Entry<K, V> higherEntry(K key) {
4004             return new CheckedMap.CheckedEntrySet.CheckedEntry(nm.higherEntry(key), valueType);
4005         }
4006 
4007         @Override
4008         public K higherKey(K key) {
4009             return nm.higherKey(key);
4010         }
4011 
4012         @Override
4013         public Entry<K, V> firstEntry() {
4014             return new CheckedMap.CheckedEntrySet.CheckedEntry(nm.firstEntry(), valueType);
4015         }
4016 
4017         @Override
4018         public Entry<K, V> lastEntry() {
4019             return new CheckedMap.CheckedEntrySet.CheckedEntry(nm.lastEntry(), valueType);
4020         }
4021 
4022         @Override
4023         public Entry<K, V> pollFirstEntry() {
4024             Entry<K,V> entry = nm.pollFirstEntry();
4025             return (null == entry) ? null : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType);
4026         }
4027 
4028         @Override
4029         public Entry<K, V> pollLastEntry() {
4030             Entry<K,V> entry = nm.pollLastEntry();
4031             return (null == entry) ? null : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType);
4032         }
4033 
4034         @Override
4035         public NavigableMap<K, V> descendingMap() {
4036             return checkedNavigableMap(nm.descendingMap(), keyType, valueType);
4037         }
4038 
4039         @Override
4040         public NavigableSet<K> navigableKeySet() {
4041             return checkedNavigableSet(nm.navigableKeySet(), keyType);
4042         }
4043 
4044         @Override
4045         public NavigableSet<K> descendingKeySet() {
4046             return checkedNavigableSet(nm.descendingKeySet(), keyType);
4047         }
4048 
4049         @Override
4050         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
4051             return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType);
4052         }
4053 
4054         @Override
4055         public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
4056             return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType);
4057         }
4058 
4059         @Override
4060         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
4061             return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType);
4062         }
4063     }
4064 
4065     // Empty collections
4066 
4067     /**
4068      * Returns an iterator that has no elements.  More precisely,
4069      *
4070      * <ul compact>
4071      *
4072      * <li>{@link Iterator#hasNext hasNext} always returns {@code
4073      * false}.
4074      *
4075      * <li>{@link Iterator#next next} always throws {@link
4076      * NoSuchElementException}.
4077      *
4078      * <li>{@link Iterator#remove remove} always throws {@link
4079      * IllegalStateException}.
4080      *
4081      * </ul>
4082      *
4083      * <p>Implementations of this method are permitted, but not
4084      * required, to return the same object from multiple invocations.
4085      *
4086      * @return an empty iterator
4087      * @since 1.7
4088      */
4089     @SuppressWarnings("unchecked")
4090     public static <T> Iterator<T> emptyIterator() {
4091         return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;
4092     }
4093 
4094     private static class EmptyIterator<E> implements Iterator<E> {
4095         static final EmptyIterator<Object> EMPTY_ITERATOR
4096             = new EmptyIterator<>();
4097 
4098         public boolean hasNext() { return false; }
4099         public E next() { throw new NoSuchElementException(); }
4100         public void remove() { throw new IllegalStateException(); }
4101         @Override
4102         public void forEachRemaining(Consumer<? super E> action) {
4103             Objects.requireNonNull(action);
4104         }
4105     }
4106 
4107     /**
4108      * Returns a list iterator that has no elements.  More precisely,
4109      *
4110      * <ul compact>
4111      *


4244 
4245         // Override default methods in Collection
4246         @Override
4247         public void forEach(Consumer<? super E> action) {
4248             Objects.requireNonNull(action);
4249         }
4250         @Override
4251         public boolean removeIf(Predicate<? super E> filter) {
4252             Objects.requireNonNull(filter);
4253             return false;
4254         }
4255         @Override
4256         public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4257 
4258         // Preserves singleton property
4259         private Object readResolve() {
4260             return EMPTY_SET;
4261         }
4262     }
4263 
4264     private static final EmptyNavigableSet<?> EMPTY_NAVIGABLE_SET =
4265         new EmptyNavigableSet<>();
4266 
4267     /**
4268      * Returns the empty sorted set (immutable).  This set is serializable.
4269      *
4270      * <p>This example illustrates the type-safe way to obtain an empty
4271      * sorted set:
4272      * <pre> {@code
4273      *     SortedSet<String> s = Collections.emptySortedSet();
4274      * }</pre>
4275      *
4276      * @implNote Implementations of this method need not create a separate
4277      * {@code SortedSet} object for each call.
4278      *
4279      * @since 1.8
4280      */
4281     @SuppressWarnings("unchecked")
4282     public static <E> SortedSet<E> emptySortedSet() {
4283         return (SortedSet<E>) EMPTY_NAVIGABLE_SET;
4284     }
4285 
4286     /**
4287      * Returns the empty navigable set (immutable).  This set is serializable.
4288      *
4289      * <p>This example illustrates the type-safe way to obtain an empty
4290      * navigable set:
4291      * <pre> {@code
4292      *     NavigableSet<String> s = Collections.emptyNavigableSet();
4293      * }</pre>
4294      *
4295      * @implNote Implementations of this method need not
4296      * create a separate {@code NavigableSet} object for each call.
4297      *
4298      * @since 1.8
4299      */
4300     @SuppressWarnings("unchecked")
4301     public static <E>NavigableSet<E> emptyNavigableSet() {
4302         return (NavigableSet<E>) EMPTY_NAVIGABLE_SET;
4303     }
4304 
4305     /**
4306      * @serial include
4307      */
4308     private static class EmptyNavigableSet<E>
4309         extends EmptySet<E>
4310         implements NavigableSet<E>, Serializable
4311     {
4312         // private static final long serialVersionUID = 6316515401502265487L;






4313 
4314         public boolean contains(Object obj) {
4315             Comparable<E> e = (Comparable<E>) obj;
4316             return obj != e;

4317         }
4318 
4319         // Preserves singleton property
4320         private Object readResolve() {
4321             return Collections.emptyNavigableSet();
4322         }
4323 
4324         @Override
4325         public Comparator<? super E> comparator() {
4326             return null;
4327         }
4328 
4329         @Override
4330         @SuppressWarnings("unchecked")
4331         public SortedSet<E> subSet(E fromElement, E toElement) {
4332             return subSet(fromElement, true, toElement, false);
4333         }
4334 
4335         @Override
4336         public SortedSet<E> headSet(E toElement) {
4337            return headSet(toElement, false);

4338         }
4339 
4340         @Override
4341         public SortedSet<E> tailSet(E fromElement) {
4342             return tailSet(fromElement, true);

4343         }
4344 
4345         @Override
4346         public E first() {
4347             throw new NoSuchElementException();
4348         }
4349 
4350         @Override
4351         public E last() {
4352             throw new NoSuchElementException();
4353         }
4354 
4355         @Override
4356         public E lower(E e) {
4357             Objects.requireNonNull(e);
4358             return null;
4359         }
4360 
4361         @Override
4362         public E floor(E e) {
4363             Objects.requireNonNull(e);
4364             return null;
4365         }
4366 
4367         @Override
4368         public E ceiling(E e) {
4369             Objects.requireNonNull(e);
4370             return null;
4371         }
4372 
4373         @Override
4374         public E higher(E e) {
4375             Objects.requireNonNull(e);
4376             return null;
4377         }
4378 
4379         @Override
4380         public E pollFirst() {
4381             return null;
4382         }
4383 
4384         @Override
4385         public E pollLast() {
4386             return null;
4387         }
4388 
4389         @Override
4390         public NavigableSet<E> descendingSet() {
4391                 return new BoundedEmptyNavigableSet(null, true, null, true, true);
4392         }
4393 
4394         @Override
4395         public Iterator<E> descendingIterator() { return emptyIterator(); }
4396 
4397         @Override
4398         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
4399             return new BoundedEmptyNavigableSet(
4400                 (Comparable<E>) Objects.requireNonNull(fromElement), fromInclusive,
4401                 (Comparable<E>) Objects.requireNonNull(toElement), toInclusive,
4402                 false);
4403         }
4404 
4405         @Override
4406         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
4407             return new BoundedEmptyNavigableSet(
4408                 null, true,
4409                 (Comparable<E>) Objects.requireNonNull(toElement), inclusive,
4410                 false);
4411         }
4412 
4413         @Override
4414         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
4415             return new BoundedEmptyNavigableSet(
4416                 (Comparable<E>) Objects.requireNonNull(fromElement), inclusive,
4417                 null, true, false);
4418         }
4419 
4420         // Override default methods in Collection
4421         @Override
4422         public void forEach(Consumer<? super E> action) {
4423             Objects.requireNonNull(action);
4424         }
4425 
4426         @Override
4427         public boolean removeIf(Predicate<? super E> filter) {
4428             Objects.requireNonNull(filter);
4429             return false;
4430         }
4431 
4432         @Override
4433         public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4434     }
4435 
4436     /**
4437      * The empty list (immutable).  This list is serializable.


4512         @Override
4513         public void sort(Comparator<? super E> c) {
4514             Objects.requireNonNull(c);
4515         }
4516 
4517         // Override default methods in Collection
4518         @Override
4519         public void forEach(Consumer<? super E> action) {
4520             Objects.requireNonNull(action);
4521         }
4522 
4523         @Override
4524         public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4525 
4526         // Preserves singleton property
4527         private Object readResolve() {
4528             return EMPTY_LIST;
4529         }
4530     }
4531 
4532     private static class BoundedEmptyNavigableSet<E> extends EmptyNavigableSet<E>
4533         implements Serializable {
4534 
4535         final boolean descending;
4536         final boolean lowerInclusive;
4537         final boolean upperInclusive;
4538         final Comparable<E> lowerBound;
4539         final Comparable<E> upperBound;
4540 
4541         public BoundedEmptyNavigableSet(
4542             Comparable<E> fromElement, boolean lowerInclusive,
4543             Comparable<E> toElement, boolean upperInclusive,
4544             boolean descending) {
4545             this.descending = descending;
4546 
4547             if ((fromElement != null) && (toElement != null))  {
4548                 int fromCompared = Integer.signum(fromElement.compareTo((E)toElement));
4549                 int toCompared = Integer.signum(toElement.compareTo((E)fromElement));
4550 
4551                 if(fromCompared != -toCompared) {
4552                     throw new IllegalArgumentException("inconsistent compareTo");
4553                 }
4554 
4555                 if (!descending) {
4556                     if (fromCompared > 0) {
4557                         throw new IllegalArgumentException();
4558                     }
4559                 } else {
4560                     if (fromCompared < 0) {
4561                         throw new IllegalArgumentException();
4562                     }
4563                 }
4564             }
4565 
4566             this.lowerBound = fromElement;
4567             this.lowerInclusive = lowerInclusive;
4568             this.upperBound = toElement;
4569             this.upperInclusive = upperInclusive;
4570         }
4571 
4572         @Override
4573         public Comparator<E> comparator() {
4574             return descending ? Collections.reverseOrder() : null;
4575         }
4576 
4577         public NavigableSet<E> descendingSet() {
4578             return new BoundedEmptyNavigableSet(upperBound, upperInclusive, lowerBound, lowerInclusive, !descending);
4579         }
4580 
4581         @Override
4582         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
4583             return new BoundedEmptyNavigableSet(inBounds(fromElement), fromInclusive, inBounds(toElement), toInclusive, descending);
4584         }
4585 
4586         @Override
4587         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
4588             return new BoundedEmptyNavigableSet(lowerBound, lowerInclusive, inBounds(toElement), inclusive, descending);
4589         }
4590 
4591         @Override
4592         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
4593             return new BoundedEmptyNavigableSet(inBounds(fromElement), inclusive, upperBound, upperInclusive, descending);
4594         }
4595 
4596         private Comparable<E> inBounds(E element) {
4597             if (!descending) {
4598                 if (null != lowerBound) {
4599                     if (lowerInclusive) {
4600                         if (lowerBound.compareTo(element) > 0) {
4601                             throw new IllegalArgumentException("out of bounds");
4602                         }
4603                     } else {
4604                         if (lowerBound.compareTo(element) >= 0) {
4605                             throw new IllegalArgumentException("out of bounds");
4606                         }
4607                     }
4608                 }
4609 
4610                 if (null != upperBound) {
4611                     if (upperInclusive) {
4612                         if (upperBound.compareTo(element) < 0) {
4613                             throw new IllegalArgumentException("out of bounds");
4614                         }
4615                     } else {
4616                         if (upperBound.compareTo(element) <= 0) {
4617                             throw new IllegalArgumentException("out of bounds");
4618                         }
4619                     }
4620                 }
4621             } else {
4622                 if (null != lowerBound) {
4623                     if (lowerInclusive) {
4624                         if (lowerBound.compareTo(element) < 0) {
4625                             throw new IllegalArgumentException("out of bounds");
4626                         }
4627                     } else {
4628                         if (lowerBound.compareTo(element) <= 0) {
4629                             throw new IllegalArgumentException("out of bounds");
4630                         }
4631                     }
4632                 }
4633 
4634                 if (null != upperBound) {
4635                     if (upperInclusive) {
4636                         if (upperBound.compareTo(element) > 0) {
4637                             throw new IllegalArgumentException("out of bounds");
4638                         }
4639                     } else {
4640                         if (upperBound.compareTo(element) >= 0) {
4641                             throw new IllegalArgumentException("out of bounds");
4642                         }
4643                     }
4644                 }
4645             }
4646 
4647             return (Comparable<E>)Objects.requireNonNull(element);
4648         }
4649     }
4650 
4651 private static class BoundedEmptyNavigableMap<K,V> extends EmptyNavigableMap<K,V>
4652         implements Serializable {
4653 
4654         final boolean descending;
4655         final boolean lowerInclusive;
4656         final boolean upperInclusive;
4657         final Comparable<K> lowerBound;
4658         final Comparable<K> upperBound;
4659 
4660         public BoundedEmptyNavigableMap(
4661             Comparable<K> fromElement, boolean lowerInclusive,
4662             Comparable<K> toElement, boolean upperInclusive,
4663             boolean descending) {
4664             this.descending = descending;
4665 
4666             if ((fromElement != null) && (toElement != null))  {
4667                 int fromCompared = Integer.signum(fromElement.compareTo((K)toElement));
4668                 int toCompared = Integer.signum(toElement.compareTo((K)fromElement));
4669 
4670                 if(fromCompared != -toCompared) {
4671                     throw new IllegalArgumentException("inconsistent compareTo");
4672                 }
4673 
4674                 if (!descending) {
4675                     if (fromCompared > 0) {
4676                         throw new IllegalArgumentException();
4677                     }
4678                 } else {
4679                     if (fromCompared < 0) {
4680                         throw new IllegalArgumentException();
4681                     }
4682                 }
4683             }
4684 
4685             this.lowerBound = fromElement;
4686             this.lowerInclusive = lowerInclusive;
4687             this.upperBound = toElement;
4688             this.upperInclusive = upperInclusive;
4689         }
4690 
4691         @Override
4692         public Comparator<? super K> comparator() {
4693             return descending ? Collections.reverseOrder() : null;
4694         }
4695 
4696         @Override
4697         public boolean containsKey(Object obj) {
4698             Comparable<K> e = (Comparable<K>) obj;
4699             return obj != e;
4700         }
4701 
4702         private Comparable<K> inBounds(K element) {
4703             if (!descending) {
4704                 if (null != lowerBound) {
4705                     if (lowerInclusive) {
4706                         if (lowerBound.compareTo(element) > 0) {
4707                             throw new IllegalArgumentException("out of bounds");
4708                         }
4709                     } else {
4710                         if (lowerBound.compareTo(element) >= 0) {
4711                             throw new IllegalArgumentException("out of bounds");
4712                         }
4713                     }
4714                 }
4715 
4716                 if (null != upperBound) {
4717                     if (upperInclusive) {
4718                         if (upperBound.compareTo(element) < 0) {
4719                             throw new IllegalArgumentException("out of bounds");
4720                         }
4721                     } else {
4722                         if (upperBound.compareTo(element) <= 0) {
4723                             throw new IllegalArgumentException("out of bounds");
4724                         }
4725                     }
4726                 }
4727             } else {
4728                 if (null != lowerBound) {
4729                     if (lowerInclusive) {
4730                         if (lowerBound.compareTo(element) < 0) {
4731                             throw new IllegalArgumentException("out of bounds");
4732                         }
4733                     } else {
4734                         if (lowerBound.compareTo(element) <= 0) {
4735                             throw new IllegalArgumentException("out of bounds");
4736                         }
4737                     }
4738                 }
4739 
4740                 if (null != upperBound) {
4741                     if (upperInclusive) {
4742                         if (upperBound.compareTo(element) > 0) {
4743                             throw new IllegalArgumentException("out of bounds");
4744                         }
4745                     } else {
4746                         if (upperBound.compareTo(element) >= 0) {
4747                             throw new IllegalArgumentException("out of bounds");
4748                         }
4749                     }
4750                 }
4751             }
4752 
4753             return (Comparable<K>)Objects.requireNonNull(element);
4754         }
4755 
4756         @Override
4757         public NavigableMap<K, V> descendingMap() {
4758             if (upperBound == null && lowerBound == null && descending) {
4759                 return Collections.emptyNavigableMap();
4760             }
4761             return new BoundedEmptyNavigableMap(upperBound, upperInclusive, lowerBound, lowerInclusive, !descending);
4762         }
4763 
4764         @Override
4765         public NavigableSet<K> navigableKeySet() {
4766             if (upperBound == null && lowerBound == null && !descending) {
4767                 return Collections.emptyNavigableSet();
4768             }
4769             return new BoundedEmptyNavigableSet(lowerBound, lowerInclusive, upperBound, upperInclusive, descending);
4770         }
4771 
4772         @Override
4773         public NavigableSet<K> descendingKeySet() {
4774             if (upperBound == null && lowerBound == null && descending) {
4775                 return Collections.emptyNavigableSet();
4776             }
4777             return new BoundedEmptyNavigableSet(upperBound, upperInclusive, lowerBound, lowerInclusive, !descending);
4778         }
4779 
4780         @Override
4781         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
4782             return new BoundedEmptyNavigableMap(inBounds(fromKey), fromInclusive, inBounds(toKey), toInclusive, descending);
4783         }
4784 
4785         @Override
4786         public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
4787             return new BoundedEmptyNavigableMap(lowerBound, lowerInclusive, inBounds(toKey), inclusive, descending);
4788         }
4789 
4790         @Override
4791         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
4792             return new BoundedEmptyNavigableMap(inBounds(fromKey), inclusive, upperBound, upperInclusive, descending);
4793         }
4794     }
4795 
4796     /**
4797      * The empty map (immutable).  This map is serializable.
4798      *
4799      * @see #emptyMap()
4800      * @since 1.3
4801      */
4802     @SuppressWarnings("rawtypes")
4803     public static final Map EMPTY_MAP = new EmptyMap<>();
4804 
4805     /**
4806      * Returns the empty map (immutable).  This map is serializable.
4807      *
4808      * <p>This example illustrates the type-safe way to obtain an empty map:
4809      * <pre>
4810      *     Map&lt;String, Date&gt; s = Collections.emptyMap();
4811      * </pre>
4812      * Implementation note:  Implementations of this method need not
4813      * create a separate <tt>Map</tt> object for each call.   Using this
4814      * method is likely to have comparable cost to using the like-named
4815      * field.  (Unlike this method, the field does not provide type safety.)
4816      *
4817      * @see #EMPTY_MAP
4818      * @since 1.5
4819      */
4820     @SuppressWarnings("unchecked")
4821     public static final <K,V> Map<K,V> emptyMap() {
4822         return (Map<K,V>) EMPTY_MAP;
4823     }
4824 
4825     /**
4826      * Returns the empty sorted map (immutable).  This map is serializable.
4827      *
4828      * <p>This example illustrates the type-safe way to obtain an empty map:
4829      * <pre> {@code
4830      *     SortedMap<String, Date> s = Collections.emptySortedMap();
4831      * }</pre>
4832      *
4833      * @implNote Implementations of this method need not create a separate
4834      * {@code SortedMap} object for each call.
4835      *
4836      * @since 1.8
4837      */
4838     @SuppressWarnings("unchecked")
4839     public static final <K,V> SortedMap<K,V> emptySortedMap() {
4840         return (SortedMap<K,V>) EMPTY_NAVIGABLE_MAP;
4841     }
4842 
4843     @SuppressWarnings("rawtypes")
4844     private static final NavigableMap EMPTY_NAVIGABLE_MAP =
4845             new EmptyNavigableMap();
4846 
4847     /**
4848      * Returns the empty navigable map (immutable).  This map is serializable.
4849      *
4850      * <p>This example illustrates the type-safe way to obtain an empty map:
4851      * <pre> {@code
4852      *     NavigableMap<String, Date> s = Collections.emptyNavigableMap();
4853      * }</pre>
4854      *
4855      * @implNote Implementations of this method need not create a separate
4856      * {@code NavigableMap} object for each call.
4857      *
4858      * @since 1.8
4859      */
4860     @SuppressWarnings("unchecked")
4861     public static final <K,V> NavigableMap<K,V> emptyNavigableMap() {
4862         return (NavigableMap<K,V>) EMPTY_NAVIGABLE_MAP;
4863     }
4864 
4865     /**
4866      * @serial include
4867      */
4868     private static class EmptyMap<K,V>
4869         extends AbstractMap<K,V>
4870         implements Serializable
4871     {
4872         private static final long serialVersionUID = 6428348081105594320L;
4873 
4874         public int size()                          {return 0;}
4875         public boolean isEmpty()                   {return true;}
4876         public boolean containsKey(Object key)     {return false;}
4877         public boolean containsValue(Object value) {return false;}
4878         public V get(Object key)                   {return null;}
4879         public Set<K> keySet()                     {return emptySet();}
4880         public Collection<V> values()              {return emptySet();}
4881         public Set<Map.Entry<K,V>> entrySet()      {return emptySet();}
4882 
4883         public boolean equals(Object o) {
4884             return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
4885         }


4933         public V computeIfPresent(K key,
4934                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4935             throw new UnsupportedOperationException();
4936         }
4937 
4938         @Override
4939         public V compute(K key,
4940                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4941             throw new UnsupportedOperationException();
4942         }
4943 
4944         @Override
4945         public V merge(K key, V value,
4946                 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
4947             throw new UnsupportedOperationException();
4948         }
4949 
4950         // Preserves singleton property
4951         private Object readResolve() {
4952             return EMPTY_MAP;
4953         }
4954     }
4955 
4956     private static class EmptyNavigableMap<K,V> extends EmptyMap<K,V>
4957         implements NavigableMap<K,V>, Serializable {
4958 
4959         EmptyNavigableMap() {
4960 
4961         }
4962 
4963         // Preserves singleton property
4964         private Object readResolve() {
4965             return Collections.emptyNavigableMap();
4966         }
4967 
4968         @Override
4969         public Entry<K, V> lowerEntry(K key) {
4970             return null;
4971         }
4972 
4973         @Override
4974         public K lowerKey(K key) {
4975             return null;
4976         }
4977 
4978         @Override
4979         public Entry<K, V> floorEntry(K key) {
4980             return null;
4981         }
4982 
4983         @Override
4984         public K floorKey(K key) {
4985             return null;
4986         }
4987 
4988         @Override
4989         public Entry<K, V> ceilingEntry(K key) {
4990             return null;
4991         }
4992 
4993         @Override
4994         public K ceilingKey(K key) {
4995             return null;
4996         }
4997 
4998         @Override
4999         public Entry<K, V> higherEntry(K key) {
5000             return null;
5001         }
5002 
5003         @Override
5004         public K higherKey(K key) {
5005             return null;
5006         }
5007 
5008         @Override
5009         public Entry<K, V> firstEntry() {
5010             return null;
5011         }
5012 
5013         @Override
5014         public Entry<K, V> lastEntry() {
5015             return null;
5016         }
5017 
5018         @Override
5019         public Entry<K, V> pollFirstEntry() {
5020             throw new UnsupportedOperationException();
5021         }
5022 
5023         @Override
5024         public Entry<K, V> pollLastEntry() {
5025             throw new UnsupportedOperationException();
5026         }
5027 
5028         @Override
5029         public NavigableMap<K, V> descendingMap() {
5030             return new BoundedEmptyNavigableMap<>(null, true, null, true, true);
5031         }
5032 
5033         @Override
5034         public NavigableSet<K> navigableKeySet() {
5035             return Collections.emptyNavigableSet();
5036         }
5037 
5038         @Override
5039         public NavigableSet<K> descendingKeySet() {
5040             return Collections.<K>emptyNavigableSet().descendingSet();
5041         }
5042 
5043         @Override
5044         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
5045             return new BoundedEmptyNavigableMap<>((Comparable<K>) fromKey, fromInclusive, (Comparable<K>) toKey, toInclusive, false);
5046         }
5047 
5048         @Override
5049         public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
5050             return new BoundedEmptyNavigableMap<>(null, false, (Comparable<K>) toKey, inclusive, false);
5051         }
5052 
5053         @Override
5054         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
5055             return new BoundedEmptyNavigableMap<>((Comparable<K>) fromKey, inclusive, null, false, false);
5056         }
5057 
5058         @Override
5059         public SortedMap<K, V> subMap(K fromKey, K toKey) {
5060             return subMap(fromKey, true, toKey, false);
5061         }
5062 
5063         @Override
5064         public SortedMap<K, V> headMap(K toKey) {
5065             return headMap(toKey, false);
5066         }
5067 
5068         @Override
5069         public SortedMap<K, V> tailMap(K fromKey) {
5070             return tailMap(fromKey, true);
5071         }
5072 
5073         @Override
5074         public Comparator<? super K> comparator() {
5075             return null;
5076         }
5077 
5078         @Override
5079         public K firstKey() {
5080             return null;
5081         }
5082 
5083         @Override
5084         public K lastKey() {
5085             return null;
5086         }
5087     }
5088 
5089     // Singleton collections
5090 
5091     /**
5092      * Returns an immutable set containing only the specified object.
5093      * The returned set is serializable.
5094      *
5095      * @param o the sole object to be stored in the returned set.
5096      * @return an immutable set containing only the specified object.
5097      */
5098     public static <T> Set<T> singleton(T o) {
5099         return new SingletonSet<>(o);
5100     }
5101 
5102     static <E> Iterator<E> singletonIterator(final E e) {
5103         return new Iterator<E>() {
5104             private boolean hasNext = true;
5105             public boolean hasNext() {