1004 * {@code Object}'s {@code equals} and {@code hashCode} methods. This
1005 * is necessary to preserve the contracts of these operations in the case
1006 * that the backing collection is a set or a list.<p>
1007 *
1008 * The returned collection will be serializable if the specified collection
1009 * is serializable.
1010 *
1011 * @param <T> the class of the objects in the collection
1012 * @param c the collection for which an unmodifiable view is to be
1013 * returned.
1014 * @return an unmodifiable view of the specified collection.
1015 */
1016 public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
1017 return new UnmodifiableCollection<>(c);
1018 }
1019
1020 /**
1021 * @serial include
1022 */
1023 static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
1024 private static final long serialVersionUID = 1820017752578914078L;
1025
1026 final Collection<? extends E> c;
1027
1028 UnmodifiableCollection(Collection<? extends E> c) {
1029 if (c==null)
1030 throw new NullPointerException();
1031 this.c = c;
1032 }
1033
1034 public int size() {return c.size();}
1035 public boolean isEmpty() {return c.isEmpty();}
1036 public boolean contains(Object o) {return c.contains(o);}
1037 public Object[] toArray() {return c.toArray();}
1038 public <T> T[] toArray(T[] a) {return c.toArray(a);}
1039 public <T> T[] toArray(IntFunction<T[]> f) {return c.toArray(f);}
1040 public String toString() {return c.toString();}
1041
1042 public Iterator<E> iterator() {
1043 return new Iterator<E>() {
1110 * specified set. Query operations on the returned set "read through" to the specified
1111 * set, and attempts to modify the returned set, whether direct or via its
1112 * iterator, result in an {@code UnsupportedOperationException}.<p>
1113 *
1114 * The returned set will be serializable if the specified set
1115 * is serializable.
1116 *
1117 * @param <T> the class of the objects in the set
1118 * @param s the set for which an unmodifiable view is to be returned.
1119 * @return an unmodifiable view of the specified set.
1120 */
1121 public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1122 return new UnmodifiableSet<>(s);
1123 }
1124
1125 /**
1126 * @serial include
1127 */
1128 static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1129 implements Set<E>, Serializable {
1130 private static final long serialVersionUID = -9215047833775013803L;
1131
1132 UnmodifiableSet(Set<? extends E> s) {super(s);}
1133 public boolean equals(Object o) {return o == this || c.equals(o);}
1134 public int hashCode() {return c.hashCode();}
1135 }
1136
1137 /**
1138 * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1139 * specified sorted set. Query operations on the returned sorted set "read
1140 * through" to the specified sorted set. Attempts to modify the returned
1141 * sorted set, whether direct, via its iterator, or via its
1142 * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
1143 * an {@code UnsupportedOperationException}.<p>
1144 *
1145 * The returned sorted set will be serializable if the specified sorted set
1146 * is serializable.
1147 *
1148 * @param <T> the class of the objects in the set
1149 * @param s the sorted set for which an unmodifiable view is to be
1150 * returned.
1151 * @return an unmodifiable view of the specified sorted set.
1152 */
1153 public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1154 return new UnmodifiableSortedSet<>(s);
1155 }
1156
1157 /**
1158 * @serial include
1159 */
1160 static class UnmodifiableSortedSet<E>
1161 extends UnmodifiableSet<E>
1162 implements SortedSet<E>, Serializable {
1163 private static final long serialVersionUID = -4929149591599911165L;
1164 private final SortedSet<E> ss;
1165
1166 UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1167
1168 public Comparator<? super E> comparator() {return ss.comparator();}
1169
1170 public SortedSet<E> subSet(E fromElement, E toElement) {
1171 return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
1172 }
1173 public SortedSet<E> headSet(E toElement) {
1174 return new UnmodifiableSortedSet<>(ss.headSet(toElement));
1175 }
1176 public SortedSet<E> tailSet(E fromElement) {
1177 return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
1178 }
1179
1180 public E first() {return ss.first();}
1181 public E last() {return ss.last();}
1182 }
1195 * @param <T> the class of the objects in the set
1196 * @param s the navigable set for which an unmodifiable view is to be
1197 * returned
1198 * @return an unmodifiable view of the specified navigable set
1199 * @since 1.8
1200 */
1201 public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) {
1202 return new UnmodifiableNavigableSet<>(s);
1203 }
1204
1205 /**
1206 * Wraps a navigable set and disables all of the mutative operations.
1207 *
1208 * @param <E> type of elements
1209 * @serial include
1210 */
1211 static class UnmodifiableNavigableSet<E>
1212 extends UnmodifiableSortedSet<E>
1213 implements NavigableSet<E>, Serializable {
1214
1215 private static final long serialVersionUID = -6027448201786391929L;
1216
1217 /**
1218 * A singleton empty unmodifiable navigable set used for
1219 * {@link #emptyNavigableSet()}.
1220 *
1221 * @param <E> type of elements, if there were any, and bounds
1222 */
1223 private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E>
1224 implements Serializable {
1225 private static final long serialVersionUID = -6291252904449939134L;
1226
1227 public EmptyNavigableSet() {
1228 super(new TreeSet<>());
1229 }
1230
1231 private Object readResolve() { return EMPTY_NAVIGABLE_SET; }
1232 }
1233
1234 @SuppressWarnings("rawtypes")
1235 private static final NavigableSet<?> EMPTY_NAVIGABLE_SET =
1236 new EmptyNavigableSet<>();
1237
1238 /**
1239 * The instance we are protecting.
1240 */
1241 private final NavigableSet<E> ns;
1242
1243 UnmodifiableNavigableSet(NavigableSet<E> s) {super(s); ns = s;}
1244
1245 public E lower(E e) { return ns.lower(e); }
1246 public E floor(E e) { return ns.floor(e); }
1247 public E ceiling(E e) { return ns.ceiling(e); }
1248 public E higher(E e) { return ns.higher(e); }
1249 public E pollFirst() { throw new UnsupportedOperationException(); }
1250 public E pollLast() { throw new UnsupportedOperationException(); }
1278 *
1279 * The returned list will be serializable if the specified list
1280 * is serializable. Similarly, the returned list will implement
1281 * {@link RandomAccess} if the specified list does.
1282 *
1283 * @param <T> the class of the objects in the list
1284 * @param list the list for which an unmodifiable view is to be returned.
1285 * @return an unmodifiable view of the specified list.
1286 */
1287 public static <T> List<T> unmodifiableList(List<? extends T> list) {
1288 return (list instanceof RandomAccess ?
1289 new UnmodifiableRandomAccessList<>(list) :
1290 new UnmodifiableList<>(list));
1291 }
1292
1293 /**
1294 * @serial include
1295 */
1296 static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1297 implements List<E> {
1298 private static final long serialVersionUID = -283967356065247728L;
1299
1300 final List<? extends E> list;
1301
1302 UnmodifiableList(List<? extends E> list) {
1303 super(list);
1304 this.list = list;
1305 }
1306
1307 public boolean equals(Object o) {return o == this || list.equals(o);}
1308 public int hashCode() {return list.hashCode();}
1309
1310 public E get(int index) {return list.get(index);}
1311 public E set(int index, E element) {
1312 throw new UnsupportedOperationException();
1313 }
1314 public void add(int index, E element) {
1315 throw new UnsupportedOperationException();
1316 }
1317 public E remove(int index) {
1362 }
1363 };
1364 }
1365
1366 public List<E> subList(int fromIndex, int toIndex) {
1367 return new UnmodifiableList<>(list.subList(fromIndex, toIndex));
1368 }
1369
1370 /**
1371 * UnmodifiableRandomAccessList instances are serialized as
1372 * UnmodifiableList instances to allow them to be deserialized
1373 * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
1374 * This method inverts the transformation. As a beneficial
1375 * side-effect, it also grafts the RandomAccess marker onto
1376 * UnmodifiableList instances that were serialized in pre-1.4 JREs.
1377 *
1378 * Note: Unfortunately, UnmodifiableRandomAccessList instances
1379 * serialized in 1.4.1 and deserialized in 1.4 will become
1380 * UnmodifiableList instances, as this method was missing in 1.4.
1381 */
1382 private Object readResolve() {
1383 return (list instanceof RandomAccess
1384 ? new UnmodifiableRandomAccessList<>(list)
1385 : this);
1386 }
1387 }
1388
1389 /**
1390 * @serial include
1391 */
1392 static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
1393 implements RandomAccess
1394 {
1395 UnmodifiableRandomAccessList(List<? extends E> list) {
1396 super(list);
1397 }
1398
1399 public List<E> subList(int fromIndex, int toIndex) {
1400 return new UnmodifiableRandomAccessList<>(
1401 list.subList(fromIndex, toIndex));
1402 }
1403
1404 private static final long serialVersionUID = -2542308836966382001L;
1405
1406 /**
1407 * Allows instances to be deserialized in pre-1.4 JREs (which do
1408 * not have UnmodifiableRandomAccessList). UnmodifiableList has
1409 * a readResolve method that inverts this transformation upon
1410 * deserialization.
1411 */
1412 private Object writeReplace() {
1413 return new UnmodifiableList<>(list);
1414 }
1415 }
1416
1417 /**
1418 * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1419 * specified map. Query operations on the returned map "read through"
1420 * to the specified map, and attempts to modify the returned
1421 * map, whether direct or via its collection views, result in an
1422 * {@code UnsupportedOperationException}.<p>
1423 *
1424 * The returned map will be serializable if the specified map
1425 * is serializable.
1426 *
1427 * @param <K> the class of the map keys
1428 * @param <V> the class of the map values
1429 * @param m the map for which an unmodifiable view is to be returned.
1430 * @return an unmodifiable view of the specified map.
1431 */
1432 public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1433 return new UnmodifiableMap<>(m);
1434 }
1435
1436 /**
1437 * @serial include
1438 */
1439 private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1440 private static final long serialVersionUID = -1034234728574286014L;
1441
1442 private final Map<? extends K, ? extends V> m;
1443
1444 UnmodifiableMap(Map<? extends K, ? extends V> m) {
1445 if (m==null)
1446 throw new NullPointerException();
1447 this.m = m;
1448 }
1449
1450 public int size() {return m.size();}
1451 public boolean isEmpty() {return m.isEmpty();}
1452 public boolean containsKey(Object key) {return m.containsKey(key);}
1453 public boolean containsValue(Object val) {return m.containsValue(val);}
1454 public V get(Object key) {return m.get(key);}
1455
1456 public V put(K key, V value) {
1457 throw new UnsupportedOperationException();
1458 }
1459 public V remove(Object key) {
1546 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1547 throw new UnsupportedOperationException();
1548 }
1549
1550 @Override
1551 public V merge(K key, V value,
1552 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1553 throw new UnsupportedOperationException();
1554 }
1555
1556 /**
1557 * We need this class in addition to UnmodifiableSet as
1558 * Map.Entries themselves permit modification of the backing Map
1559 * via their setValue operation. This class is subtle: there are
1560 * many possible attacks that must be thwarted.
1561 *
1562 * @serial include
1563 */
1564 static class UnmodifiableEntrySet<K,V>
1565 extends UnmodifiableSet<Map.Entry<K,V>> {
1566 private static final long serialVersionUID = 7854390611657943733L;
1567
1568 @SuppressWarnings({"unchecked", "rawtypes"})
1569 UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
1570 // Need to cast to raw in order to work around a limitation in the type system
1571 super((Set)s);
1572 }
1573
1574 static <K, V> Consumer<Map.Entry<? extends K, ? extends V>> entryConsumer(
1575 Consumer<? super Entry<K, V>> action) {
1576 return e -> action.accept(new UnmodifiableEntry<>(e));
1577 }
1578
1579 public void forEach(Consumer<? super Entry<K, V>> action) {
1580 Objects.requireNonNull(action);
1581 c.forEach(entryConsumer(action));
1582 }
1583
1584 static final class UnmodifiableEntrySetSpliterator<K, V>
1585 implements Spliterator<Entry<K,V>> {
1777 *
1778 * The returned sorted map will be serializable if the specified sorted map
1779 * is serializable.
1780 *
1781 * @param <K> the class of the map keys
1782 * @param <V> the class of the map values
1783 * @param m the sorted map for which an unmodifiable view is to be
1784 * returned.
1785 * @return an unmodifiable view of the specified sorted map.
1786 */
1787 public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1788 return new UnmodifiableSortedMap<>(m);
1789 }
1790
1791 /**
1792 * @serial include
1793 */
1794 static class UnmodifiableSortedMap<K,V>
1795 extends UnmodifiableMap<K,V>
1796 implements SortedMap<K,V>, Serializable {
1797 private static final long serialVersionUID = -8806743815996713206L;
1798
1799 private final SortedMap<K, ? extends V> sm;
1800
1801 UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m; }
1802 public Comparator<? super K> comparator() { return sm.comparator(); }
1803 public SortedMap<K,V> subMap(K fromKey, K toKey)
1804 { return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); }
1805 public SortedMap<K,V> headMap(K toKey)
1806 { return new UnmodifiableSortedMap<>(sm.headMap(toKey)); }
1807 public SortedMap<K,V> tailMap(K fromKey)
1808 { return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); }
1809 public K firstKey() { return sm.firstKey(); }
1810 public K lastKey() { return sm.lastKey(); }
1811 }
1812
1813 /**
1814 * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1815 * specified navigable map. Query operations on the returned navigable map "read
1816 * through" to the specified navigable map. Attempts to modify the returned
1821 * The returned navigable map will be serializable if the specified
1822 * navigable map is serializable.
1823 *
1824 * @param <K> the class of the map keys
1825 * @param <V> the class of the map values
1826 * @param m the navigable map for which an unmodifiable view is to be
1827 * returned
1828 * @return an unmodifiable view of the specified navigable map
1829 * @since 1.8
1830 */
1831 public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {
1832 return new UnmodifiableNavigableMap<>(m);
1833 }
1834
1835 /**
1836 * @serial include
1837 */
1838 static class UnmodifiableNavigableMap<K,V>
1839 extends UnmodifiableSortedMap<K,V>
1840 implements NavigableMap<K,V>, Serializable {
1841 private static final long serialVersionUID = -4858195264774772197L;
1842
1843 /**
1844 * A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve
1845 * to preserve singleton property.
1846 *
1847 * @param <K> type of keys, if there were any, and of bounds
1848 * @param <V> type of values, if there were any
1849 */
1850 private static class EmptyNavigableMap<K,V> extends UnmodifiableNavigableMap<K,V>
1851 implements Serializable {
1852
1853 private static final long serialVersionUID = -2239321462712562324L;
1854
1855 EmptyNavigableMap() { super(new TreeMap<>()); }
1856
1857 @Override
1858 public NavigableSet<K> navigableKeySet()
1859 { return emptyNavigableSet(); }
1860
1861 private Object readResolve() { return EMPTY_NAVIGABLE_MAP; }
1862 }
1863
1864 /**
1865 * Singleton for {@link emptyNavigableMap()} which is also immutable.
1866 */
1867 private static final EmptyNavigableMap<?,?> EMPTY_NAVIGABLE_MAP =
1868 new EmptyNavigableMap<>();
1869
1870 /**
1871 * The instance we wrap and protect.
1872 */
1873 private final NavigableMap<K, ? extends V> nm;
1874
1875 UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m)
1876 {super(m); nm = m;}
1877
1878 public K lowerKey(K key) { return nm.lowerKey(key); }
1879 public K floorKey(K key) { return nm.floorKey(key); }
1880 public K ceilingKey(K key) { return nm.ceilingKey(key); }
1981 *
1982 * The returned collection will be serializable if the specified collection
1983 * is serializable.
1984 *
1985 * @param <T> the class of the objects in the collection
1986 * @param c the collection to be "wrapped" in a synchronized collection.
1987 * @return a synchronized view of the specified collection.
1988 */
1989 public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
1990 return new SynchronizedCollection<>(c);
1991 }
1992
1993 static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
1994 return new SynchronizedCollection<>(c, mutex);
1995 }
1996
1997 /**
1998 * @serial include
1999 */
2000 static class SynchronizedCollection<E> implements Collection<E>, Serializable {
2001 private static final long serialVersionUID = 3053995032091335093L;
2002
2003 final Collection<E> c; // Backing Collection
2004 final Object mutex; // Object on which to synchronize
2005
2006 SynchronizedCollection(Collection<E> c) {
2007 this.c = Objects.requireNonNull(c);
2008 mutex = this;
2009 }
2010
2011 SynchronizedCollection(Collection<E> c, Object mutex) {
2012 this.c = Objects.requireNonNull(c);
2013 this.mutex = Objects.requireNonNull(mutex);
2014 }
2015
2016 public int size() {
2017 synchronized (mutex) {return c.size();}
2018 }
2019 public boolean isEmpty() {
2020 synchronized (mutex) {return c.isEmpty();}
2065 @Override
2066 public void forEach(Consumer<? super E> consumer) {
2067 synchronized (mutex) {c.forEach(consumer);}
2068 }
2069 @Override
2070 public boolean removeIf(Predicate<? super E> filter) {
2071 synchronized (mutex) {return c.removeIf(filter);}
2072 }
2073 @Override
2074 public Spliterator<E> spliterator() {
2075 return c.spliterator(); // Must be manually synched by user!
2076 }
2077 @Override
2078 public Stream<E> stream() {
2079 return c.stream(); // Must be manually synched by user!
2080 }
2081 @Override
2082 public Stream<E> parallelStream() {
2083 return c.parallelStream(); // Must be manually synched by user!
2084 }
2085 private void writeObject(ObjectOutputStream s) throws IOException {
2086 synchronized (mutex) {s.defaultWriteObject();}
2087 }
2088 }
2089
2090 /**
2091 * Returns a synchronized (thread-safe) set backed by the specified
2092 * set. In order to guarantee serial access, it is critical that
2093 * <strong>all</strong> access to the backing set is accomplished
2094 * through the returned set.<p>
2095 *
2096 * It is imperative that the user manually synchronize on the returned
2097 * collection when traversing it via {@link Iterator}, {@link Spliterator}
2098 * or {@link Stream}:
2099 * <pre>
2100 * Set s = Collections.synchronizedSet(new HashSet());
2101 * ...
2102 * synchronized (s) {
2103 * Iterator i = s.iterator(); // Must be in the synchronized block
2104 * while (i.hasNext())
2111 * serializable.
2112 *
2113 * @param <T> the class of the objects in the set
2114 * @param s the set to be "wrapped" in a synchronized set.
2115 * @return a synchronized view of the specified set.
2116 */
2117 public static <T> Set<T> synchronizedSet(Set<T> s) {
2118 return new SynchronizedSet<>(s);
2119 }
2120
2121 static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
2122 return new SynchronizedSet<>(s, mutex);
2123 }
2124
2125 /**
2126 * @serial include
2127 */
2128 static class SynchronizedSet<E>
2129 extends SynchronizedCollection<E>
2130 implements Set<E> {
2131 private static final long serialVersionUID = 487447009682186044L;
2132
2133 SynchronizedSet(Set<E> s) {
2134 super(s);
2135 }
2136 SynchronizedSet(Set<E> s, Object mutex) {
2137 super(s, mutex);
2138 }
2139
2140 public boolean equals(Object o) {
2141 if (this == o)
2142 return true;
2143 synchronized (mutex) {return c.equals(o);}
2144 }
2145 public int hashCode() {
2146 synchronized (mutex) {return c.hashCode();}
2147 }
2148 }
2149
2150 /**
2180 * Failure to follow this advice may result in non-deterministic behavior.
2181 *
2182 * <p>The returned sorted set will be serializable if the specified
2183 * sorted set is serializable.
2184 *
2185 * @param <T> the class of the objects in the set
2186 * @param s the sorted set to be "wrapped" in a synchronized sorted set.
2187 * @return a synchronized view of the specified sorted set.
2188 */
2189 public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
2190 return new SynchronizedSortedSet<>(s);
2191 }
2192
2193 /**
2194 * @serial include
2195 */
2196 static class SynchronizedSortedSet<E>
2197 extends SynchronizedSet<E>
2198 implements SortedSet<E>
2199 {
2200 private static final long serialVersionUID = 8695801310862127406L;
2201
2202 private final SortedSet<E> ss;
2203
2204 SynchronizedSortedSet(SortedSet<E> s) {
2205 super(s);
2206 ss = s;
2207 }
2208 SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
2209 super(s, mutex);
2210 ss = s;
2211 }
2212
2213 public Comparator<? super E> comparator() {
2214 synchronized (mutex) {return ss.comparator();}
2215 }
2216
2217 public SortedSet<E> subSet(E fromElement, E toElement) {
2218 synchronized (mutex) {
2219 return new SynchronizedSortedSet<>(
2274 * <p>The returned navigable set will be serializable if the specified
2275 * navigable set is serializable.
2276 *
2277 * @param <T> the class of the objects in the set
2278 * @param s the navigable set to be "wrapped" in a synchronized navigable
2279 * set
2280 * @return a synchronized view of the specified navigable set
2281 * @since 1.8
2282 */
2283 public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) {
2284 return new SynchronizedNavigableSet<>(s);
2285 }
2286
2287 /**
2288 * @serial include
2289 */
2290 static class SynchronizedNavigableSet<E>
2291 extends SynchronizedSortedSet<E>
2292 implements NavigableSet<E>
2293 {
2294 private static final long serialVersionUID = -5505529816273629798L;
2295
2296 private final NavigableSet<E> ns;
2297
2298 SynchronizedNavigableSet(NavigableSet<E> s) {
2299 super(s);
2300 ns = s;
2301 }
2302
2303 SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) {
2304 super(s, mutex);
2305 ns = s;
2306 }
2307 public E lower(E e) { synchronized (mutex) {return ns.lower(e);} }
2308 public E floor(E e) { synchronized (mutex) {return ns.floor(e);} }
2309 public E ceiling(E e) { synchronized (mutex) {return ns.ceiling(e);} }
2310 public E higher(E e) { synchronized (mutex) {return ns.higher(e);} }
2311 public E pollFirst() { synchronized (mutex) {return ns.pollFirst();} }
2312 public E pollLast() { synchronized (mutex) {return ns.pollLast();} }
2313
2383 * @return a synchronized view of the specified list.
2384 */
2385 public static <T> List<T> synchronizedList(List<T> list) {
2386 return (list instanceof RandomAccess ?
2387 new SynchronizedRandomAccessList<>(list) :
2388 new SynchronizedList<>(list));
2389 }
2390
2391 static <T> List<T> synchronizedList(List<T> list, Object mutex) {
2392 return (list instanceof RandomAccess ?
2393 new SynchronizedRandomAccessList<>(list, mutex) :
2394 new SynchronizedList<>(list, mutex));
2395 }
2396
2397 /**
2398 * @serial include
2399 */
2400 static class SynchronizedList<E>
2401 extends SynchronizedCollection<E>
2402 implements List<E> {
2403 private static final long serialVersionUID = -7754090372962971524L;
2404
2405 final List<E> list;
2406
2407 SynchronizedList(List<E> list) {
2408 super(list);
2409 this.list = list;
2410 }
2411 SynchronizedList(List<E> list, Object mutex) {
2412 super(list, mutex);
2413 this.list = list;
2414 }
2415
2416 public boolean equals(Object o) {
2417 if (this == o)
2418 return true;
2419 synchronized (mutex) {return list.equals(o);}
2420 }
2421 public int hashCode() {
2422 synchronized (mutex) {return list.hashCode();}
2465 public void replaceAll(UnaryOperator<E> operator) {
2466 synchronized (mutex) {list.replaceAll(operator);}
2467 }
2468 @Override
2469 public void sort(Comparator<? super E> c) {
2470 synchronized (mutex) {list.sort(c);}
2471 }
2472
2473 /**
2474 * SynchronizedRandomAccessList instances are serialized as
2475 * SynchronizedList instances to allow them to be deserialized
2476 * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
2477 * This method inverts the transformation. As a beneficial
2478 * side-effect, it also grafts the RandomAccess marker onto
2479 * SynchronizedList instances that were serialized in pre-1.4 JREs.
2480 *
2481 * Note: Unfortunately, SynchronizedRandomAccessList instances
2482 * serialized in 1.4.1 and deserialized in 1.4 will become
2483 * SynchronizedList instances, as this method was missing in 1.4.
2484 */
2485 private Object readResolve() {
2486 return (list instanceof RandomAccess
2487 ? new SynchronizedRandomAccessList<>(list)
2488 : this);
2489 }
2490 }
2491
2492 /**
2493 * @serial include
2494 */
2495 static class SynchronizedRandomAccessList<E>
2496 extends SynchronizedList<E>
2497 implements RandomAccess {
2498
2499 SynchronizedRandomAccessList(List<E> list) {
2500 super(list);
2501 }
2502
2503 SynchronizedRandomAccessList(List<E> list, Object mutex) {
2504 super(list, mutex);
2505 }
2506
2507 public List<E> subList(int fromIndex, int toIndex) {
2508 synchronized (mutex) {
2509 return new SynchronizedRandomAccessList<>(
2510 list.subList(fromIndex, toIndex), mutex);
2511 }
2512 }
2513
2514 private static final long serialVersionUID = 1530674583602358482L;
2515
2516 /**
2517 * Allows instances to be deserialized in pre-1.4 JREs (which do
2518 * not have SynchronizedRandomAccessList). SynchronizedList has
2519 * a readResolve method that inverts this transformation upon
2520 * deserialization.
2521 */
2522 private Object writeReplace() {
2523 return new SynchronizedList<>(list);
2524 }
2525 }
2526
2527 /**
2528 * Returns a synchronized (thread-safe) map backed by the specified
2529 * map. In order to guarantee serial access, it is critical that
2530 * <strong>all</strong> access to the backing map is accomplished
2531 * through the returned map.<p>
2532 *
2533 * It is imperative that the user manually synchronize on the returned
2534 * map when traversing any of its collection views via {@link Iterator},
2535 * {@link Spliterator} or {@link Stream}:
2536 * <pre>
2537 * Map m = Collections.synchronizedMap(new HashMap());
2538 * ...
2539 * Set s = m.keySet(); // Needn't be in synchronized block
2540 * ...
2541 * synchronized (m) { // Synchronizing on m, not s!
2546 * </pre>
2547 * Failure to follow this advice may result in non-deterministic behavior.
2548 *
2549 * <p>The returned map will be serializable if the specified map is
2550 * serializable.
2551 *
2552 * @param <K> the class of the map keys
2553 * @param <V> the class of the map values
2554 * @param m the map to be "wrapped" in a synchronized map.
2555 * @return a synchronized view of the specified map.
2556 */
2557 public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
2558 return new SynchronizedMap<>(m);
2559 }
2560
2561 /**
2562 * @serial include
2563 */
2564 private static class SynchronizedMap<K,V>
2565 implements Map<K,V>, Serializable {
2566 private static final long serialVersionUID = 1978198479659022715L;
2567
2568 private final Map<K,V> m; // Backing Map
2569 final Object mutex; // Object on which to synchronize
2570
2571 SynchronizedMap(Map<K,V> m) {
2572 this.m = Objects.requireNonNull(m);
2573 mutex = this;
2574 }
2575
2576 SynchronizedMap(Map<K,V> m, Object mutex) {
2577 this.m = m;
2578 this.mutex = mutex;
2579 }
2580
2581 public int size() {
2582 synchronized (mutex) {return m.size();}
2583 }
2584 public boolean isEmpty() {
2585 synchronized (mutex) {return m.isEmpty();}
2680 public V computeIfAbsent(K key,
2681 Function<? super K, ? extends V> mappingFunction) {
2682 synchronized (mutex) {return m.computeIfAbsent(key, mappingFunction);}
2683 }
2684 @Override
2685 public V computeIfPresent(K key,
2686 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2687 synchronized (mutex) {return m.computeIfPresent(key, remappingFunction);}
2688 }
2689 @Override
2690 public V compute(K key,
2691 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2692 synchronized (mutex) {return m.compute(key, remappingFunction);}
2693 }
2694 @Override
2695 public V merge(K key, V value,
2696 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2697 synchronized (mutex) {return m.merge(key, value, remappingFunction);}
2698 }
2699
2700 private void writeObject(ObjectOutputStream s) throws IOException {
2701 synchronized (mutex) {s.defaultWriteObject();}
2702 }
2703 }
2704
2705 /**
2706 * Returns a synchronized (thread-safe) sorted map backed by the specified
2707 * sorted map. In order to guarantee serial access, it is critical that
2708 * <strong>all</strong> access to the backing sorted map is accomplished
2709 * through the returned sorted map (or its views).<p>
2710 *
2711 * It is imperative that the user manually synchronize on the returned
2712 * sorted map when traversing any of its collection views, or the
2713 * collections views of any of its {@code subMap}, {@code headMap} or
2714 * {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or
2715 * {@link Stream}:
2716 * <pre>
2717 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2718 * ...
2719 * Set s = m.keySet(); // Needn't be in synchronized block
2741 *
2742 * <p>The returned sorted map will be serializable if the specified
2743 * sorted map is serializable.
2744 *
2745 * @param <K> the class of the map keys
2746 * @param <V> the class of the map values
2747 * @param m the sorted map to be "wrapped" in a synchronized sorted map.
2748 * @return a synchronized view of the specified sorted map.
2749 */
2750 public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
2751 return new SynchronizedSortedMap<>(m);
2752 }
2753
2754 /**
2755 * @serial include
2756 */
2757 static class SynchronizedSortedMap<K,V>
2758 extends SynchronizedMap<K,V>
2759 implements SortedMap<K,V>
2760 {
2761 private static final long serialVersionUID = -8798146769416483793L;
2762
2763 private final SortedMap<K,V> sm;
2764
2765 SynchronizedSortedMap(SortedMap<K,V> m) {
2766 super(m);
2767 sm = m;
2768 }
2769 SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
2770 super(m, mutex);
2771 sm = m;
2772 }
2773
2774 public Comparator<? super K> comparator() {
2775 synchronized (mutex) {return sm.comparator();}
2776 }
2777
2778 public SortedMap<K,V> subMap(K fromKey, K toKey) {
2779 synchronized (mutex) {
2780 return new SynchronizedSortedMap<>(
2843 * @param <K> the class of the map keys
2844 * @param <V> the class of the map values
2845 * @param m the navigable map to be "wrapped" in a synchronized navigable
2846 * map
2847 * @return a synchronized view of the specified navigable map.
2848 * @since 1.8
2849 */
2850 public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) {
2851 return new SynchronizedNavigableMap<>(m);
2852 }
2853
2854 /**
2855 * A synchronized NavigableMap.
2856 *
2857 * @serial include
2858 */
2859 static class SynchronizedNavigableMap<K,V>
2860 extends SynchronizedSortedMap<K,V>
2861 implements NavigableMap<K,V>
2862 {
2863 private static final long serialVersionUID = 699392247599746807L;
2864
2865 private final NavigableMap<K,V> nm;
2866
2867 SynchronizedNavigableMap(NavigableMap<K,V> m) {
2868 super(m);
2869 nm = m;
2870 }
2871 SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) {
2872 super(m, mutex);
2873 nm = m;
2874 }
2875
2876 public Entry<K, V> lowerEntry(K key)
2877 { synchronized (mutex) { return nm.lowerEntry(key); } }
2878 public K lowerKey(K key)
2879 { synchronized (mutex) { return nm.lowerKey(key); } }
2880 public Entry<K, V> floorEntry(K key)
2881 { synchronized (mutex) { return nm.floorEntry(key); } }
2882 public K floorKey(K key)
3021 * @param c the collection for which a dynamically typesafe view is to be
3022 * returned
3023 * @param type the type of element that {@code c} is permitted to hold
3024 * @return a dynamically typesafe view of the specified collection
3025 * @since 1.5
3026 */
3027 public static <E> Collection<E> checkedCollection(Collection<E> c,
3028 Class<E> type) {
3029 return new CheckedCollection<>(c, type);
3030 }
3031
3032 @SuppressWarnings("unchecked")
3033 static <T> T[] zeroLengthArray(Class<T> type) {
3034 return (T[]) Array.newInstance(type, 0);
3035 }
3036
3037 /**
3038 * @serial include
3039 */
3040 static class CheckedCollection<E> implements Collection<E>, Serializable {
3041 private static final long serialVersionUID = 1578914078182001775L;
3042
3043 final Collection<E> c;
3044 final Class<E> type;
3045
3046 @SuppressWarnings("unchecked")
3047 E typeCheck(Object o) {
3048 if (o != null && !type.isInstance(o))
3049 throw new ClassCastException(badElementMsg(o));
3050 return (E) o;
3051 }
3052
3053 private String badElementMsg(Object o) {
3054 return "Attempt to insert " + o.getClass() +
3055 " element into collection with element type " + type;
3056 }
3057
3058 CheckedCollection(Collection<E> c, Class<E> type) {
3059 this.c = Objects.requireNonNull(c, "c");
3060 this.type = Objects.requireNonNull(type, "type");
3170 * whenever the backing queue does.
3171 *
3172 * @param <E> the class of the objects in the queue
3173 * @param queue the queue for which a dynamically typesafe view is to be
3174 * returned
3175 * @param type the type of element that {@code queue} is permitted to hold
3176 * @return a dynamically typesafe view of the specified queue
3177 * @since 1.8
3178 */
3179 public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type) {
3180 return new CheckedQueue<>(queue, type);
3181 }
3182
3183 /**
3184 * @serial include
3185 */
3186 static class CheckedQueue<E>
3187 extends CheckedCollection<E>
3188 implements Queue<E>, Serializable
3189 {
3190 private static final long serialVersionUID = 1433151992604707767L;
3191 final Queue<E> queue;
3192
3193 CheckedQueue(Queue<E> queue, Class<E> elementType) {
3194 super(queue, elementType);
3195 this.queue = queue;
3196 }
3197
3198 public E element() {return queue.element();}
3199 public boolean equals(Object o) {return o == this || c.equals(o);}
3200 public int hashCode() {return c.hashCode();}
3201 public E peek() {return queue.peek();}
3202 public E poll() {return queue.poll();}
3203 public E remove() {return queue.remove();}
3204 public boolean offer(E e) {return queue.offer(typeCheck(e));}
3205 }
3206
3207 /**
3208 * Returns a dynamically typesafe view of the specified set.
3209 * Any attempt to insert an element of the wrong type will result in
3224 * type, the returned set permits insertion of null elements whenever
3225 * the backing set does.
3226 *
3227 * @param <E> the class of the objects in the set
3228 * @param s the set for which a dynamically typesafe view is to be
3229 * returned
3230 * @param type the type of element that {@code s} is permitted to hold
3231 * @return a dynamically typesafe view of the specified set
3232 * @since 1.5
3233 */
3234 public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
3235 return new CheckedSet<>(s, type);
3236 }
3237
3238 /**
3239 * @serial include
3240 */
3241 static class CheckedSet<E> extends CheckedCollection<E>
3242 implements Set<E>, Serializable
3243 {
3244 private static final long serialVersionUID = 4694047833775013803L;
3245
3246 CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
3247
3248 public boolean equals(Object o) { return o == this || c.equals(o); }
3249 public int hashCode() { return c.hashCode(); }
3250 }
3251
3252 /**
3253 * Returns a dynamically typesafe view of the specified sorted set.
3254 * Any attempt to insert an element of the wrong type will result in an
3255 * immediate {@link ClassCastException}. Assuming a sorted set
3256 * contains no incorrectly typed elements prior to the time a
3257 * dynamically typesafe view is generated, and that all subsequent
3258 * access to the sorted set takes place through the view, it is
3259 * <i>guaranteed</i> that the sorted set cannot contain an incorrectly
3260 * typed element.
3261 *
3262 * <p>A discussion of the use of dynamically typesafe views may be
3263 * found in the documentation for the {@link #checkedCollection
3271 * whenever the backing sorted set does.
3272 *
3273 * @param <E> the class of the objects in the set
3274 * @param s the sorted set for which a dynamically typesafe view is to be
3275 * returned
3276 * @param type the type of element that {@code s} is permitted to hold
3277 * @return a dynamically typesafe view of the specified sorted set
3278 * @since 1.5
3279 */
3280 public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
3281 Class<E> type) {
3282 return new CheckedSortedSet<>(s, type);
3283 }
3284
3285 /**
3286 * @serial include
3287 */
3288 static class CheckedSortedSet<E> extends CheckedSet<E>
3289 implements SortedSet<E>, Serializable
3290 {
3291 private static final long serialVersionUID = 1599911165492914959L;
3292
3293 private final SortedSet<E> ss;
3294
3295 CheckedSortedSet(SortedSet<E> s, Class<E> type) {
3296 super(s, type);
3297 ss = s;
3298 }
3299
3300 public Comparator<? super E> comparator() { return ss.comparator(); }
3301 public E first() { return ss.first(); }
3302 public E last() { return ss.last(); }
3303
3304 public SortedSet<E> subSet(E fromElement, E toElement) {
3305 return checkedSortedSet(ss.subSet(fromElement,toElement), type);
3306 }
3307 public SortedSet<E> headSet(E toElement) {
3308 return checkedSortedSet(ss.headSet(toElement), type);
3309 }
3310 public SortedSet<E> tailSet(E fromElement) {
3334 * whenever the backing sorted set does.
3335 *
3336 * @param <E> the class of the objects in the set
3337 * @param s the navigable set for which a dynamically typesafe view is to be
3338 * returned
3339 * @param type the type of element that {@code s} is permitted to hold
3340 * @return a dynamically typesafe view of the specified navigable set
3341 * @since 1.8
3342 */
3343 public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,
3344 Class<E> type) {
3345 return new CheckedNavigableSet<>(s, type);
3346 }
3347
3348 /**
3349 * @serial include
3350 */
3351 static class CheckedNavigableSet<E> extends CheckedSortedSet<E>
3352 implements NavigableSet<E>, Serializable
3353 {
3354 private static final long serialVersionUID = -5429120189805438922L;
3355
3356 private final NavigableSet<E> ns;
3357
3358 CheckedNavigableSet(NavigableSet<E> s, Class<E> type) {
3359 super(s, type);
3360 ns = s;
3361 }
3362
3363 public E lower(E e) { return ns.lower(e); }
3364 public E floor(E e) { return ns.floor(e); }
3365 public E ceiling(E e) { return ns.ceiling(e); }
3366 public E higher(E e) { return ns.higher(e); }
3367 public E pollFirst() { return ns.pollFirst(); }
3368 public E pollLast() {return ns.pollLast(); }
3369 public NavigableSet<E> descendingSet()
3370 { return checkedNavigableSet(ns.descendingSet(), type); }
3371 public Iterator<E> descendingIterator()
3372 {return checkedNavigableSet(ns.descendingSet(), type).iterator(); }
3373
3417 * @param <E> the class of the objects in the list
3418 * @param list the list for which a dynamically typesafe view is to be
3419 * returned
3420 * @param type the type of element that {@code list} is permitted to hold
3421 * @return a dynamically typesafe view of the specified list
3422 * @since 1.5
3423 */
3424 public static <E> List<E> checkedList(List<E> list, Class<E> type) {
3425 return (list instanceof RandomAccess ?
3426 new CheckedRandomAccessList<>(list, type) :
3427 new CheckedList<>(list, type));
3428 }
3429
3430 /**
3431 * @serial include
3432 */
3433 static class CheckedList<E>
3434 extends CheckedCollection<E>
3435 implements List<E>
3436 {
3437 private static final long serialVersionUID = 65247728283967356L;
3438 final List<E> list;
3439
3440 CheckedList(List<E> list, Class<E> type) {
3441 super(list, type);
3442 this.list = list;
3443 }
3444
3445 public boolean equals(Object o) { return o == this || list.equals(o); }
3446 public int hashCode() { return list.hashCode(); }
3447 public E get(int index) { return list.get(index); }
3448 public E remove(int index) { return list.remove(index); }
3449 public int indexOf(Object o) { return list.indexOf(o); }
3450 public int lastIndexOf(Object o) { return list.lastIndexOf(o); }
3451
3452 public E set(int index, E element) {
3453 return list.set(index, typeCheck(element));
3454 }
3455
3456 public void add(int index, E element) {
3502 * already been replaced.
3503 */
3504 @Override
3505 public void replaceAll(UnaryOperator<E> operator) {
3506 Objects.requireNonNull(operator);
3507 list.replaceAll(e -> typeCheck(operator.apply(e)));
3508 }
3509
3510 @Override
3511 public void sort(Comparator<? super E> c) {
3512 list.sort(c);
3513 }
3514 }
3515
3516 /**
3517 * @serial include
3518 */
3519 static class CheckedRandomAccessList<E> extends CheckedList<E>
3520 implements RandomAccess
3521 {
3522 private static final long serialVersionUID = 1638200125423088369L;
3523
3524 CheckedRandomAccessList(List<E> list, Class<E> type) {
3525 super(list, type);
3526 }
3527
3528 public List<E> subList(int fromIndex, int toIndex) {
3529 return new CheckedRandomAccessList<>(
3530 list.subList(fromIndex, toIndex), type);
3531 }
3532 }
3533
3534 /**
3535 * Returns a dynamically typesafe view of the specified map.
3536 * Any attempt to insert a mapping whose key or value have the wrong
3537 * type will result in an immediate {@link ClassCastException}.
3538 * Similarly, any attempt to modify the value currently associated with
3539 * a key will result in an immediate {@link ClassCastException},
3540 * whether the modification is attempted directly through the map
3541 * itself, or through a {@link Map.Entry} instance obtained from the
3563 * @param m the map for which a dynamically typesafe view is to be
3564 * returned
3565 * @param keyType the type of key that {@code m} is permitted to hold
3566 * @param valueType the type of value that {@code m} is permitted to hold
3567 * @return a dynamically typesafe view of the specified map
3568 * @since 1.5
3569 */
3570 public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
3571 Class<K> keyType,
3572 Class<V> valueType) {
3573 return new CheckedMap<>(m, keyType, valueType);
3574 }
3575
3576
3577 /**
3578 * @serial include
3579 */
3580 private static class CheckedMap<K,V>
3581 implements Map<K,V>, Serializable
3582 {
3583 private static final long serialVersionUID = 5742860141034234728L;
3584
3585 private final Map<K, V> m;
3586 final Class<K> keyType;
3587 final Class<V> valueType;
3588
3589 private void typeCheck(Object key, Object value) {
3590 if (key != null && !keyType.isInstance(key))
3591 throw new ClassCastException(badKeyMsg(key));
3592
3593 if (value != null && !valueType.isInstance(value))
3594 throw new ClassCastException(badValueMsg(value));
3595 }
3596
3597 private BiFunction<? super K, ? super V, ? extends V> typeCheck(
3598 BiFunction<? super K, ? super V, ? extends V> func) {
3599 Objects.requireNonNull(func);
3600 return (k, v) -> {
3601 V newValue = func.apply(k, v);
3602 typeCheck(k, newValue);
3962 * @param <V> the class of the map values
3963 * @param m the map for which a dynamically typesafe view is to be
3964 * returned
3965 * @param keyType the type of key that {@code m} is permitted to hold
3966 * @param valueType the type of value that {@code m} is permitted to hold
3967 * @return a dynamically typesafe view of the specified map
3968 * @since 1.5
3969 */
3970 public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
3971 Class<K> keyType,
3972 Class<V> valueType) {
3973 return new CheckedSortedMap<>(m, keyType, valueType);
3974 }
3975
3976 /**
3977 * @serial include
3978 */
3979 static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
3980 implements SortedMap<K,V>, Serializable
3981 {
3982 private static final long serialVersionUID = 1599671320688067438L;
3983
3984 private final SortedMap<K, V> sm;
3985
3986 CheckedSortedMap(SortedMap<K, V> m,
3987 Class<K> keyType, Class<V> valueType) {
3988 super(m, keyType, valueType);
3989 sm = m;
3990 }
3991
3992 public Comparator<? super K> comparator() { return sm.comparator(); }
3993 public K firstKey() { return sm.firstKey(); }
3994 public K lastKey() { return sm.lastKey(); }
3995
3996 public SortedMap<K,V> subMap(K fromKey, K toKey) {
3997 return checkedSortedMap(sm.subMap(fromKey, toKey),
3998 keyType, valueType);
3999 }
4000 public SortedMap<K,V> headMap(K toKey) {
4001 return checkedSortedMap(sm.headMap(toKey), keyType, valueType);
4036 * @param <V> type of map values
4037 * @param m the map for which a dynamically typesafe view is to be
4038 * returned
4039 * @param keyType the type of key that {@code m} is permitted to hold
4040 * @param valueType the type of value that {@code m} is permitted to hold
4041 * @return a dynamically typesafe view of the specified map
4042 * @since 1.8
4043 */
4044 public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m,
4045 Class<K> keyType,
4046 Class<V> valueType) {
4047 return new CheckedNavigableMap<>(m, keyType, valueType);
4048 }
4049
4050 /**
4051 * @serial include
4052 */
4053 static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V>
4054 implements NavigableMap<K,V>, Serializable
4055 {
4056 private static final long serialVersionUID = -4852462692372534096L;
4057
4058 private final NavigableMap<K, V> nm;
4059
4060 CheckedNavigableMap(NavigableMap<K, V> m,
4061 Class<K> keyType, Class<V> valueType) {
4062 super(m, keyType, valueType);
4063 nm = m;
4064 }
4065
4066 public Comparator<? super K> comparator() { return nm.comparator(); }
4067 public K firstKey() { return nm.firstKey(); }
4068 public K lastKey() { return nm.lastKey(); }
4069
4070 public Entry<K, V> lowerEntry(K key) {
4071 Entry<K,V> lower = nm.lowerEntry(key);
4072 return (null != lower)
4073 ? new CheckedMap.CheckedEntrySet.CheckedEntry<>(lower, valueType)
4074 : null;
4075 }
4314 * field does not provide type safety.)
4315 *
4316 * @param <T> the class of the objects in the set
4317 * @return the empty set
4318 *
4319 * @see #EMPTY_SET
4320 * @since 1.5
4321 */
4322 @SuppressWarnings("unchecked")
4323 public static final <T> Set<T> emptySet() {
4324 return (Set<T>) EMPTY_SET;
4325 }
4326
4327 /**
4328 * @serial include
4329 */
4330 private static class EmptySet<E>
4331 extends AbstractSet<E>
4332 implements Serializable
4333 {
4334 private static final long serialVersionUID = 1582296315990362920L;
4335
4336 public Iterator<E> iterator() { return emptyIterator(); }
4337
4338 public int size() {return 0;}
4339 public boolean isEmpty() {return true;}
4340 public void clear() {}
4341
4342 public boolean contains(Object obj) {return false;}
4343 public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
4344
4345 public Object[] toArray() { return new Object[0]; }
4346
4347 public <T> T[] toArray(T[] a) {
4348 if (a.length > 0)
4349 a[0] = null;
4350 return a;
4351 }
4352
4353 // Override default methods in Collection
4354 @Override
4355 public void forEach(Consumer<? super E> action) {
4356 Objects.requireNonNull(action);
4357 }
4358 @Override
4359 public boolean removeIf(Predicate<? super E> filter) {
4360 Objects.requireNonNull(filter);
4361 return false;
4362 }
4363 @Override
4364 public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4365
4366 // Preserves singleton property
4367 private Object readResolve() {
4368 return EMPTY_SET;
4369 }
4370
4371 @Override
4372 public int hashCode() {
4373 return 0;
4374 }
4375 }
4376
4377 /**
4378 * Returns an empty sorted set (immutable). This set is serializable.
4379 *
4380 * <p>This example illustrates the type-safe way to obtain an empty
4381 * sorted set:
4382 * <pre> {@code
4383 * SortedSet<String> s = Collections.emptySortedSet();
4384 * }</pre>
4385 *
4386 * @implNote Implementations of this method need not create a separate
4438 * cost to using the like-named field. (Unlike this method, the field does
4439 * not provide type safety.)
4440 *
4441 * @param <T> type of elements, if there were any, in the list
4442 * @return an empty immutable list
4443 *
4444 * @see #EMPTY_LIST
4445 * @since 1.5
4446 */
4447 @SuppressWarnings("unchecked")
4448 public static final <T> List<T> emptyList() {
4449 return (List<T>) EMPTY_LIST;
4450 }
4451
4452 /**
4453 * @serial include
4454 */
4455 private static class EmptyList<E>
4456 extends AbstractList<E>
4457 implements RandomAccess, Serializable {
4458 private static final long serialVersionUID = 8842843931221139166L;
4459
4460 public Iterator<E> iterator() {
4461 return emptyIterator();
4462 }
4463 public ListIterator<E> listIterator() {
4464 return emptyListIterator();
4465 }
4466
4467 public int size() {return 0;}
4468 public boolean isEmpty() {return true;}
4469 public void clear() {}
4470
4471 public boolean contains(Object obj) {return false;}
4472 public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
4473
4474 public Object[] toArray() { return new Object[0]; }
4475
4476 public <T> T[] toArray(T[] a) {
4477 if (a.length > 0)
4495 return false;
4496 }
4497 @Override
4498 public void replaceAll(UnaryOperator<E> operator) {
4499 Objects.requireNonNull(operator);
4500 }
4501 @Override
4502 public void sort(Comparator<? super E> c) {
4503 }
4504
4505 // Override default methods in Collection
4506 @Override
4507 public void forEach(Consumer<? super E> action) {
4508 Objects.requireNonNull(action);
4509 }
4510
4511 @Override
4512 public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4513
4514 // Preserves singleton property
4515 private Object readResolve() {
4516 return EMPTY_LIST;
4517 }
4518 }
4519
4520 /**
4521 * The empty map (immutable). This map is serializable.
4522 *
4523 * @see #emptyMap()
4524 * @since 1.3
4525 */
4526 @SuppressWarnings("rawtypes")
4527 public static final Map EMPTY_MAP = new EmptyMap<>();
4528
4529 /**
4530 * Returns an empty map (immutable). This map is serializable.
4531 *
4532 * <p>This example illustrates the type-safe way to obtain an empty map:
4533 * <pre>
4534 * Map<String, Date> s = Collections.emptyMap();
4581 * @implNote Implementations of this method need not create a separate
4582 * {@code NavigableMap} object for each call.
4583 *
4584 * @param <K> the class of the map keys
4585 * @param <V> the class of the map values
4586 * @return an empty navigable map
4587 * @since 1.8
4588 */
4589 @SuppressWarnings("unchecked")
4590 public static final <K,V> NavigableMap<K,V> emptyNavigableMap() {
4591 return (NavigableMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;
4592 }
4593
4594 /**
4595 * @serial include
4596 */
4597 private static class EmptyMap<K,V>
4598 extends AbstractMap<K,V>
4599 implements Serializable
4600 {
4601 private static final long serialVersionUID = 6428348081105594320L;
4602
4603 public int size() {return 0;}
4604 public boolean isEmpty() {return true;}
4605 public void clear() {}
4606 public boolean containsKey(Object key) {return false;}
4607 public boolean containsValue(Object value) {return false;}
4608 public V get(Object key) {return null;}
4609 public Set<K> keySet() {return emptySet();}
4610 public Collection<V> values() {return emptySet();}
4611 public Set<Map.Entry<K,V>> entrySet() {return emptySet();}
4612
4613 public boolean equals(Object o) {
4614 return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
4615 }
4616
4617 public int hashCode() {return 0;}
4618
4619 // Override default methods in Map
4620 @Override
4661
4662 @Override
4663 public V computeIfPresent(K key,
4664 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4665 throw new UnsupportedOperationException();
4666 }
4667
4668 @Override
4669 public V compute(K key,
4670 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4671 throw new UnsupportedOperationException();
4672 }
4673
4674 @Override
4675 public V merge(K key, V value,
4676 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
4677 throw new UnsupportedOperationException();
4678 }
4679
4680 // Preserves singleton property
4681 private Object readResolve() {
4682 return EMPTY_MAP;
4683 }
4684 }
4685
4686 // Singleton collections
4687
4688 /**
4689 * Returns an immutable set containing only the specified object.
4690 * The returned set is serializable.
4691 *
4692 * @param <T> the class of the objects in the set
4693 * @param o the sole object to be stored in the returned set.
4694 * @return an immutable set containing only the specified object.
4695 */
4696 public static <T> Set<T> singleton(T o) {
4697 return new SingletonSet<>(o);
4698 }
4699
4700 static <E> Iterator<E> singletonIterator(final E e) {
4760 return est;
4761 }
4762
4763 @Override
4764 public int characteristics() {
4765 int value = (element != null) ? Spliterator.NONNULL : 0;
4766
4767 return value | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE |
4768 Spliterator.DISTINCT | Spliterator.ORDERED;
4769 }
4770 };
4771 }
4772
4773 /**
4774 * @serial include
4775 */
4776 private static class SingletonSet<E>
4777 extends AbstractSet<E>
4778 implements Serializable
4779 {
4780 private static final long serialVersionUID = 3193687207550431679L;
4781
4782 private final E element;
4783
4784 SingletonSet(E e) {element = e;}
4785
4786 public Iterator<E> iterator() {
4787 return singletonIterator(element);
4788 }
4789
4790 public int size() {return 1;}
4791
4792 public boolean contains(Object o) {return eq(o, element);}
4793
4794 // Override default methods for Collection
4795 @Override
4796 public void forEach(Consumer<? super E> action) {
4797 action.accept(element);
4798 }
4799 @Override
4813 /**
4814 * Returns an immutable list containing only the specified object.
4815 * The returned list is serializable.
4816 *
4817 * @param <T> the class of the objects in the list
4818 * @param o the sole object to be stored in the returned list.
4819 * @return an immutable list containing only the specified object.
4820 * @since 1.3
4821 */
4822 public static <T> List<T> singletonList(T o) {
4823 return new SingletonList<>(o);
4824 }
4825
4826 /**
4827 * @serial include
4828 */
4829 private static class SingletonList<E>
4830 extends AbstractList<E>
4831 implements RandomAccess, Serializable {
4832
4833 private static final long serialVersionUID = 3093736618740652951L;
4834
4835 private final E element;
4836
4837 SingletonList(E obj) {element = obj;}
4838
4839 public Iterator<E> iterator() {
4840 return singletonIterator(element);
4841 }
4842
4843 public int size() {return 1;}
4844
4845 public boolean contains(Object obj) {return eq(obj, element);}
4846
4847 public E get(int index) {
4848 if (index != 0)
4849 throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
4850 return element;
4851 }
4852
4881 * specified value. The returned map is serializable.
4882 *
4883 * @param <K> the class of the map keys
4884 * @param <V> the class of the map values
4885 * @param key the sole key to be stored in the returned map.
4886 * @param value the value to which the returned map maps {@code key}.
4887 * @return an immutable map containing only the specified key-value
4888 * mapping.
4889 * @since 1.3
4890 */
4891 public static <K,V> Map<K,V> singletonMap(K key, V value) {
4892 return new SingletonMap<>(key, value);
4893 }
4894
4895 /**
4896 * @serial include
4897 */
4898 private static class SingletonMap<K,V>
4899 extends AbstractMap<K,V>
4900 implements Serializable {
4901 private static final long serialVersionUID = -6979724477215052911L;
4902
4903 private final K k;
4904 private final V v;
4905
4906 SingletonMap(K key, V value) {
4907 k = key;
4908 v = value;
4909 }
4910
4911 public int size() {return 1;}
4912 public boolean isEmpty() {return false;}
4913 public boolean containsKey(Object key) {return eq(key, k);}
4914 public boolean containsValue(Object value) {return eq(value, v);}
4915 public V get(Object key) {return (eq(key, k) ? v : null);}
4916
4917 private transient Set<K> keySet;
4918 private transient Set<Map.Entry<K,V>> entrySet;
4919 private transient Collection<V> values;
4920
5018 * @param o the element to appear repeatedly in the returned list.
5019 * @return an immutable list consisting of {@code n} copies of the
5020 * specified object.
5021 * @throws IllegalArgumentException if {@code n < 0}
5022 * @see List#addAll(Collection)
5023 * @see List#addAll(int, Collection)
5024 */
5025 public static <T> List<T> nCopies(int n, T o) {
5026 if (n < 0)
5027 throw new IllegalArgumentException("List length = " + n);
5028 return new CopiesList<>(n, o);
5029 }
5030
5031 /**
5032 * @serial include
5033 */
5034 private static class CopiesList<E>
5035 extends AbstractList<E>
5036 implements RandomAccess, Serializable
5037 {
5038 private static final long serialVersionUID = 2739099268398711800L;
5039
5040 final int n;
5041 final E element;
5042
5043 CopiesList(int n, E e) {
5044 assert n >= 0;
5045 this.n = n;
5046 element = e;
5047 }
5048
5049 public int size() {
5050 return n;
5051 }
5052
5053 public boolean contains(Object obj) {
5054 return n != 0 && eq(obj, element);
5055 }
5056
5057 public int indexOf(Object o) {
5149 }
5150 return remaining == 0 && !itr.hasNext();
5151 }
5152
5153 // Override default methods in Collection
5154 @Override
5155 public Stream<E> stream() {
5156 return IntStream.range(0, n).mapToObj(i -> element);
5157 }
5158
5159 @Override
5160 public Stream<E> parallelStream() {
5161 return IntStream.range(0, n).parallel().mapToObj(i -> element);
5162 }
5163
5164 @Override
5165 public Spliterator<E> spliterator() {
5166 return stream().spliterator();
5167 }
5168
5169 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
5170 ois.defaultReadObject();
5171 SharedSecrets.getJavaObjectInputStreamAccess().checkArray(ois, Object[].class, n);
5172 }
5173 }
5174
5175 /**
5176 * Returns a comparator that imposes the reverse of the <em>natural
5177 * ordering</em> on a collection of objects that implement the
5178 * {@code Comparable} interface. (The natural ordering is the ordering
5179 * imposed by the objects' own {@code compareTo} method.) This enables a
5180 * simple idiom for sorting (or maintaining) collections (or arrays) of
5181 * objects that implement the {@code Comparable} interface in
5182 * reverse-natural-order. For example, suppose {@code a} is an array of
5183 * strings. Then: <pre>
5184 * Arrays.sort(a, Collections.reverseOrder());
5185 * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
5186 *
5187 * The returned comparator is serializable.
5188 *
5189 * @param <T> the class of the objects compared by the comparator
5190 * @return A comparator that imposes the reverse of the <i>natural
5191 * ordering</i> on a collection of objects that implement
5192 * the {@code Comparable} interface.
5193 * @see Comparable
5194 */
5195 @SuppressWarnings("unchecked")
5196 public static <T> Comparator<T> reverseOrder() {
5197 return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5198 }
5199
5200 /**
5201 * @serial include
5202 */
5203 private static class ReverseComparator
5204 implements Comparator<Comparable<Object>>, Serializable {
5205
5206 private static final long serialVersionUID = 7207038068494060240L;
5207
5208 static final ReverseComparator REVERSE_ORDER
5209 = new ReverseComparator();
5210
5211 public int compare(Comparable<Object> c1, Comparable<Object> c2) {
5212 return c2.compareTo(c1);
5213 }
5214
5215 private Object readResolve() { return Collections.reverseOrder(); }
5216
5217 @Override
5218 public Comparator<Comparable<Object>> reversed() {
5219 return Comparator.naturalOrder();
5220 }
5221 }
5222
5223 /**
5224 * Returns a comparator that imposes the reverse ordering of the specified
5225 * comparator. If the specified comparator is {@code null}, this method is
5226 * equivalent to {@link #reverseOrder()} (in other words, it returns a
5227 * comparator that imposes the reverse of the <em>natural ordering</em> on
5228 * a collection of objects that implement the Comparable interface).
5229 *
5230 * <p>The returned comparator is serializable (assuming the specified
5231 * comparator is also serializable or {@code null}).
5232 *
5233 * @param <T> the class of the objects compared by the comparator
5234 * @param cmp a comparator who's ordering is to be reversed by the returned
5241 public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
5242 if (cmp == null) {
5243 return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5244 } else if (cmp == ReverseComparator.REVERSE_ORDER) {
5245 return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;
5246 } else if (cmp == Comparators.NaturalOrderComparator.INSTANCE) {
5247 return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5248 } else if (cmp instanceof ReverseComparator2) {
5249 return ((ReverseComparator2<T>) cmp).cmp;
5250 } else {
5251 return new ReverseComparator2<>(cmp);
5252 }
5253 }
5254
5255 /**
5256 * @serial include
5257 */
5258 private static class ReverseComparator2<T> implements Comparator<T>,
5259 Serializable
5260 {
5261 private static final long serialVersionUID = 4374092139857L;
5262
5263 /**
5264 * The comparator specified in the static factory. This will never
5265 * be null, as the static factory returns a ReverseComparator
5266 * instance if its argument is null.
5267 *
5268 * @serial
5269 */
5270 final Comparator<T> cmp;
5271
5272 ReverseComparator2(Comparator<T> cmp) {
5273 assert cmp != null;
5274 this.cmp = cmp;
5275 }
5276
5277 public int compare(T t1, T t2) {
5278 return cmp.compare(t2, t1);
5279 }
5280
5575 public boolean retainAll(Collection<?> c) {return s.retainAll(c);}
5576 // addAll is the only inherited implementation
5577
5578 // Override default methods in Collection
5579 @Override
5580 public void forEach(Consumer<? super E> action) {
5581 s.forEach(action);
5582 }
5583 @Override
5584 public boolean removeIf(Predicate<? super E> filter) {
5585 return s.removeIf(filter);
5586 }
5587
5588 @Override
5589 public Spliterator<E> spliterator() {return s.spliterator();}
5590 @Override
5591 public Stream<E> stream() {return s.stream();}
5592 @Override
5593 public Stream<E> parallelStream() {return s.parallelStream();}
5594
5595 private static final long serialVersionUID = 2454657854757543876L;
5596
5597 private void readObject(java.io.ObjectInputStream stream)
5598 throws IOException, ClassNotFoundException
5599 {
5600 stream.defaultReadObject();
5601 s = m.keySet();
5602 }
5603 }
5604
5605 /**
5606 * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
5607 * {@link Queue}. Method {@code add} is mapped to {@code push},
5608 * {@code remove} is mapped to {@code pop} and so on. This
5609 * view can be useful when you would like to use a method
5610 * requiring a {@code Queue} but you need Lifo ordering.
5611 *
5612 * <p>Each method invocation on the queue returned by this method
5613 * results in exactly one method invocation on the backing deque, with
5614 * one exception. The {@link Queue#addAll addAll} method is
5615 * implemented as a sequence of {@link Deque#addFirst addFirst}
5616 * invocations on the backing deque.
5617 *
5618 * @param <T> the class of the objects in the deque
5619 * @param deque the deque
5620 * @return the queue
5621 * @since 1.6
5622 */
5623 public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
5624 return new AsLIFOQueue<>(Objects.requireNonNull(deque));
5625 }
5626
5627 /**
5628 * @serial include
5629 */
5630 static class AsLIFOQueue<E> extends AbstractQueue<E>
5631 implements Queue<E>, Serializable {
5632 private static final long serialVersionUID = 1802017725587941708L;
5633 private final Deque<E> q;
5634 AsLIFOQueue(Deque<E> q) { this.q = q; }
5635 public boolean add(E e) { q.addFirst(e); return true; }
5636 public boolean offer(E e) { return q.offerFirst(e); }
5637 public E poll() { return q.pollFirst(); }
5638 public E remove() { return q.removeFirst(); }
5639 public E peek() { return q.peekFirst(); }
5640 public E element() { return q.getFirst(); }
5641 public void clear() { q.clear(); }
5642 public int size() { return q.size(); }
5643 public boolean isEmpty() { return q.isEmpty(); }
5644 public boolean contains(Object o) { return q.contains(o); }
5645 public boolean remove(Object o) { return q.remove(o); }
5646 public Iterator<E> iterator() { return q.iterator(); }
5647 public Object[] toArray() { return q.toArray(); }
5648 public <T> T[] toArray(T[] a) { return q.toArray(a); }
5649 public <T> T[] toArray(IntFunction<T[]> f) { return q.toArray(f); }
5650 public String toString() { return q.toString(); }
5651 public boolean containsAll(Collection<?> c) { return q.containsAll(c); }
|
1004 * {@code Object}'s {@code equals} and {@code hashCode} methods. This
1005 * is necessary to preserve the contracts of these operations in the case
1006 * that the backing collection is a set or a list.<p>
1007 *
1008 * The returned collection will be serializable if the specified collection
1009 * is serializable.
1010 *
1011 * @param <T> the class of the objects in the collection
1012 * @param c the collection for which an unmodifiable view is to be
1013 * returned.
1014 * @return an unmodifiable view of the specified collection.
1015 */
1016 public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
1017 return new UnmodifiableCollection<>(c);
1018 }
1019
1020 /**
1021 * @serial include
1022 */
1023 static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
1024 @java.io.Serial
1025 private static final long serialVersionUID = 1820017752578914078L;
1026
1027 final Collection<? extends E> c;
1028
1029 UnmodifiableCollection(Collection<? extends E> c) {
1030 if (c==null)
1031 throw new NullPointerException();
1032 this.c = c;
1033 }
1034
1035 public int size() {return c.size();}
1036 public boolean isEmpty() {return c.isEmpty();}
1037 public boolean contains(Object o) {return c.contains(o);}
1038 public Object[] toArray() {return c.toArray();}
1039 public <T> T[] toArray(T[] a) {return c.toArray(a);}
1040 public <T> T[] toArray(IntFunction<T[]> f) {return c.toArray(f);}
1041 public String toString() {return c.toString();}
1042
1043 public Iterator<E> iterator() {
1044 return new Iterator<E>() {
1111 * specified set. Query operations on the returned set "read through" to the specified
1112 * set, and attempts to modify the returned set, whether direct or via its
1113 * iterator, result in an {@code UnsupportedOperationException}.<p>
1114 *
1115 * The returned set will be serializable if the specified set
1116 * is serializable.
1117 *
1118 * @param <T> the class of the objects in the set
1119 * @param s the set for which an unmodifiable view is to be returned.
1120 * @return an unmodifiable view of the specified set.
1121 */
1122 public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1123 return new UnmodifiableSet<>(s);
1124 }
1125
1126 /**
1127 * @serial include
1128 */
1129 static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1130 implements Set<E>, Serializable {
1131 @java.io.Serial
1132 private static final long serialVersionUID = -9215047833775013803L;
1133
1134 UnmodifiableSet(Set<? extends E> s) {super(s);}
1135 public boolean equals(Object o) {return o == this || c.equals(o);}
1136 public int hashCode() {return c.hashCode();}
1137 }
1138
1139 /**
1140 * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1141 * specified sorted set. Query operations on the returned sorted set "read
1142 * through" to the specified sorted set. Attempts to modify the returned
1143 * sorted set, whether direct, via its iterator, or via its
1144 * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
1145 * an {@code UnsupportedOperationException}.<p>
1146 *
1147 * The returned sorted set will be serializable if the specified sorted set
1148 * is serializable.
1149 *
1150 * @param <T> the class of the objects in the set
1151 * @param s the sorted set for which an unmodifiable view is to be
1152 * returned.
1153 * @return an unmodifiable view of the specified sorted set.
1154 */
1155 public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1156 return new UnmodifiableSortedSet<>(s);
1157 }
1158
1159 /**
1160 * @serial include
1161 */
1162 static class UnmodifiableSortedSet<E>
1163 extends UnmodifiableSet<E>
1164 implements SortedSet<E>, Serializable {
1165 @java.io.Serial
1166 private static final long serialVersionUID = -4929149591599911165L;
1167 private final SortedSet<E> ss;
1168
1169 UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1170
1171 public Comparator<? super E> comparator() {return ss.comparator();}
1172
1173 public SortedSet<E> subSet(E fromElement, E toElement) {
1174 return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
1175 }
1176 public SortedSet<E> headSet(E toElement) {
1177 return new UnmodifiableSortedSet<>(ss.headSet(toElement));
1178 }
1179 public SortedSet<E> tailSet(E fromElement) {
1180 return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
1181 }
1182
1183 public E first() {return ss.first();}
1184 public E last() {return ss.last();}
1185 }
1198 * @param <T> the class of the objects in the set
1199 * @param s the navigable set for which an unmodifiable view is to be
1200 * returned
1201 * @return an unmodifiable view of the specified navigable set
1202 * @since 1.8
1203 */
1204 public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) {
1205 return new UnmodifiableNavigableSet<>(s);
1206 }
1207
1208 /**
1209 * Wraps a navigable set and disables all of the mutative operations.
1210 *
1211 * @param <E> type of elements
1212 * @serial include
1213 */
1214 static class UnmodifiableNavigableSet<E>
1215 extends UnmodifiableSortedSet<E>
1216 implements NavigableSet<E>, Serializable {
1217
1218 @java.io.Serial
1219 private static final long serialVersionUID = -6027448201786391929L;
1220
1221 /**
1222 * A singleton empty unmodifiable navigable set used for
1223 * {@link #emptyNavigableSet()}.
1224 *
1225 * @param <E> type of elements, if there were any, and bounds
1226 */
1227 private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E>
1228 implements Serializable {
1229 @java.io.Serial
1230 private static final long serialVersionUID = -6291252904449939134L;
1231
1232 public EmptyNavigableSet() {
1233 super(new TreeSet<>());
1234 }
1235
1236 @java.io.Serial
1237 private Object readResolve() { return EMPTY_NAVIGABLE_SET; }
1238 }
1239
1240 @SuppressWarnings("rawtypes")
1241 private static final NavigableSet<?> EMPTY_NAVIGABLE_SET =
1242 new EmptyNavigableSet<>();
1243
1244 /**
1245 * The instance we are protecting.
1246 */
1247 private final NavigableSet<E> ns;
1248
1249 UnmodifiableNavigableSet(NavigableSet<E> s) {super(s); ns = s;}
1250
1251 public E lower(E e) { return ns.lower(e); }
1252 public E floor(E e) { return ns.floor(e); }
1253 public E ceiling(E e) { return ns.ceiling(e); }
1254 public E higher(E e) { return ns.higher(e); }
1255 public E pollFirst() { throw new UnsupportedOperationException(); }
1256 public E pollLast() { throw new UnsupportedOperationException(); }
1284 *
1285 * The returned list will be serializable if the specified list
1286 * is serializable. Similarly, the returned list will implement
1287 * {@link RandomAccess} if the specified list does.
1288 *
1289 * @param <T> the class of the objects in the list
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
1299 /**
1300 * @serial include
1301 */
1302 static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1303 implements List<E> {
1304 @java.io.Serial
1305 private static final long serialVersionUID = -283967356065247728L;
1306
1307 final List<? extends E> list;
1308
1309 UnmodifiableList(List<? extends E> list) {
1310 super(list);
1311 this.list = list;
1312 }
1313
1314 public boolean equals(Object o) {return o == this || list.equals(o);}
1315 public int hashCode() {return list.hashCode();}
1316
1317 public E get(int index) {return list.get(index);}
1318 public E set(int index, E element) {
1319 throw new UnsupportedOperationException();
1320 }
1321 public void add(int index, E element) {
1322 throw new UnsupportedOperationException();
1323 }
1324 public E remove(int index) {
1369 }
1370 };
1371 }
1372
1373 public List<E> subList(int fromIndex, int toIndex) {
1374 return new UnmodifiableList<>(list.subList(fromIndex, toIndex));
1375 }
1376
1377 /**
1378 * UnmodifiableRandomAccessList instances are serialized as
1379 * UnmodifiableList instances to allow them to be deserialized
1380 * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
1381 * This method inverts the transformation. As a beneficial
1382 * side-effect, it also grafts the RandomAccess marker onto
1383 * UnmodifiableList instances that were serialized in pre-1.4 JREs.
1384 *
1385 * Note: Unfortunately, UnmodifiableRandomAccessList instances
1386 * serialized in 1.4.1 and deserialized in 1.4 will become
1387 * UnmodifiableList instances, as this method was missing in 1.4.
1388 */
1389 @java.io.Serial
1390 private Object readResolve() {
1391 return (list instanceof RandomAccess
1392 ? new UnmodifiableRandomAccessList<>(list)
1393 : this);
1394 }
1395 }
1396
1397 /**
1398 * @serial include
1399 */
1400 static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
1401 implements RandomAccess
1402 {
1403 UnmodifiableRandomAccessList(List<? extends E> list) {
1404 super(list);
1405 }
1406
1407 public List<E> subList(int fromIndex, int toIndex) {
1408 return new UnmodifiableRandomAccessList<>(
1409 list.subList(fromIndex, toIndex));
1410 }
1411
1412 @java.io.Serial
1413 private static final long serialVersionUID = -2542308836966382001L;
1414
1415 /**
1416 * Allows instances to be deserialized in pre-1.4 JREs (which do
1417 * not have UnmodifiableRandomAccessList). UnmodifiableList has
1418 * a readResolve method that inverts this transformation upon
1419 * deserialization.
1420 */
1421 @java.io.Serial
1422 private Object writeReplace() {
1423 return new UnmodifiableList<>(list);
1424 }
1425 }
1426
1427 /**
1428 * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1429 * specified map. Query operations on the returned map "read through"
1430 * to the specified map, and attempts to modify the returned
1431 * map, whether direct or via its collection views, result in an
1432 * {@code UnsupportedOperationException}.<p>
1433 *
1434 * The returned map will be serializable if the specified map
1435 * is serializable.
1436 *
1437 * @param <K> the class of the map keys
1438 * @param <V> the class of the map values
1439 * @param m the map for which an unmodifiable view is to be returned.
1440 * @return an unmodifiable view of the specified map.
1441 */
1442 public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1443 return new UnmodifiableMap<>(m);
1444 }
1445
1446 /**
1447 * @serial include
1448 */
1449 private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1450 @java.io.Serial
1451 private static final long serialVersionUID = -1034234728574286014L;
1452
1453 private final Map<? extends K, ? extends V> m;
1454
1455 UnmodifiableMap(Map<? extends K, ? extends V> m) {
1456 if (m==null)
1457 throw new NullPointerException();
1458 this.m = m;
1459 }
1460
1461 public int size() {return m.size();}
1462 public boolean isEmpty() {return m.isEmpty();}
1463 public boolean containsKey(Object key) {return m.containsKey(key);}
1464 public boolean containsValue(Object val) {return m.containsValue(val);}
1465 public V get(Object key) {return m.get(key);}
1466
1467 public V put(K key, V value) {
1468 throw new UnsupportedOperationException();
1469 }
1470 public V remove(Object key) {
1557 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1558 throw new UnsupportedOperationException();
1559 }
1560
1561 @Override
1562 public V merge(K key, V value,
1563 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1564 throw new UnsupportedOperationException();
1565 }
1566
1567 /**
1568 * We need this class in addition to UnmodifiableSet as
1569 * Map.Entries themselves permit modification of the backing Map
1570 * via their setValue operation. This class is subtle: there are
1571 * many possible attacks that must be thwarted.
1572 *
1573 * @serial include
1574 */
1575 static class UnmodifiableEntrySet<K,V>
1576 extends UnmodifiableSet<Map.Entry<K,V>> {
1577 @java.io.Serial
1578 private static final long serialVersionUID = 7854390611657943733L;
1579
1580 @SuppressWarnings({"unchecked", "rawtypes"})
1581 UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
1582 // Need to cast to raw in order to work around a limitation in the type system
1583 super((Set)s);
1584 }
1585
1586 static <K, V> Consumer<Map.Entry<? extends K, ? extends V>> entryConsumer(
1587 Consumer<? super Entry<K, V>> action) {
1588 return e -> action.accept(new UnmodifiableEntry<>(e));
1589 }
1590
1591 public void forEach(Consumer<? super Entry<K, V>> action) {
1592 Objects.requireNonNull(action);
1593 c.forEach(entryConsumer(action));
1594 }
1595
1596 static final class UnmodifiableEntrySetSpliterator<K, V>
1597 implements Spliterator<Entry<K,V>> {
1789 *
1790 * The returned sorted map will be serializable if the specified sorted map
1791 * is serializable.
1792 *
1793 * @param <K> the class of the map keys
1794 * @param <V> the class of the map values
1795 * @param m the sorted map for which an unmodifiable view is to be
1796 * returned.
1797 * @return an unmodifiable view of the specified sorted map.
1798 */
1799 public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1800 return new UnmodifiableSortedMap<>(m);
1801 }
1802
1803 /**
1804 * @serial include
1805 */
1806 static class UnmodifiableSortedMap<K,V>
1807 extends UnmodifiableMap<K,V>
1808 implements SortedMap<K,V>, Serializable {
1809 @java.io.Serial
1810 private static final long serialVersionUID = -8806743815996713206L;
1811
1812 private final SortedMap<K, ? extends V> sm;
1813
1814 UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m; }
1815 public Comparator<? super K> comparator() { return sm.comparator(); }
1816 public SortedMap<K,V> subMap(K fromKey, K toKey)
1817 { return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); }
1818 public SortedMap<K,V> headMap(K toKey)
1819 { return new UnmodifiableSortedMap<>(sm.headMap(toKey)); }
1820 public SortedMap<K,V> tailMap(K fromKey)
1821 { return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); }
1822 public K firstKey() { return sm.firstKey(); }
1823 public K lastKey() { return sm.lastKey(); }
1824 }
1825
1826 /**
1827 * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1828 * specified navigable map. Query operations on the returned navigable map "read
1829 * through" to the specified navigable map. Attempts to modify the returned
1834 * The returned navigable map will be serializable if the specified
1835 * navigable map is serializable.
1836 *
1837 * @param <K> the class of the map keys
1838 * @param <V> the class of the map values
1839 * @param m the navigable map for which an unmodifiable view is to be
1840 * returned
1841 * @return an unmodifiable view of the specified navigable map
1842 * @since 1.8
1843 */
1844 public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {
1845 return new UnmodifiableNavigableMap<>(m);
1846 }
1847
1848 /**
1849 * @serial include
1850 */
1851 static class UnmodifiableNavigableMap<K,V>
1852 extends UnmodifiableSortedMap<K,V>
1853 implements NavigableMap<K,V>, Serializable {
1854 @java.io.Serial
1855 private static final long serialVersionUID = -4858195264774772197L;
1856
1857 /**
1858 * A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve
1859 * to preserve singleton property.
1860 *
1861 * @param <K> type of keys, if there were any, and of bounds
1862 * @param <V> type of values, if there were any
1863 */
1864 private static class EmptyNavigableMap<K,V> extends UnmodifiableNavigableMap<K,V>
1865 implements Serializable {
1866
1867 @java.io.Serial
1868 private static final long serialVersionUID = -2239321462712562324L;
1869
1870 EmptyNavigableMap() { super(new TreeMap<>()); }
1871
1872 @Override
1873 public NavigableSet<K> navigableKeySet()
1874 { return emptyNavigableSet(); }
1875
1876 @java.io.Serial
1877 private Object readResolve() { return EMPTY_NAVIGABLE_MAP; }
1878 }
1879
1880 /**
1881 * Singleton for {@link emptyNavigableMap()} which is also immutable.
1882 */
1883 private static final EmptyNavigableMap<?,?> EMPTY_NAVIGABLE_MAP =
1884 new EmptyNavigableMap<>();
1885
1886 /**
1887 * The instance we wrap and protect.
1888 */
1889 private final NavigableMap<K, ? extends V> nm;
1890
1891 UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m)
1892 {super(m); nm = m;}
1893
1894 public K lowerKey(K key) { return nm.lowerKey(key); }
1895 public K floorKey(K key) { return nm.floorKey(key); }
1896 public K ceilingKey(K key) { return nm.ceilingKey(key); }
1997 *
1998 * The returned collection will be serializable if the specified collection
1999 * is serializable.
2000 *
2001 * @param <T> the class of the objects in the collection
2002 * @param c the collection to be "wrapped" in a synchronized collection.
2003 * @return a synchronized view of the specified collection.
2004 */
2005 public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
2006 return new SynchronizedCollection<>(c);
2007 }
2008
2009 static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
2010 return new SynchronizedCollection<>(c, mutex);
2011 }
2012
2013 /**
2014 * @serial include
2015 */
2016 static class SynchronizedCollection<E> implements Collection<E>, Serializable {
2017 @java.io.Serial
2018 private static final long serialVersionUID = 3053995032091335093L;
2019
2020 final Collection<E> c; // Backing Collection
2021 final Object mutex; // Object on which to synchronize
2022
2023 SynchronizedCollection(Collection<E> c) {
2024 this.c = Objects.requireNonNull(c);
2025 mutex = this;
2026 }
2027
2028 SynchronizedCollection(Collection<E> c, Object mutex) {
2029 this.c = Objects.requireNonNull(c);
2030 this.mutex = Objects.requireNonNull(mutex);
2031 }
2032
2033 public int size() {
2034 synchronized (mutex) {return c.size();}
2035 }
2036 public boolean isEmpty() {
2037 synchronized (mutex) {return c.isEmpty();}
2082 @Override
2083 public void forEach(Consumer<? super E> consumer) {
2084 synchronized (mutex) {c.forEach(consumer);}
2085 }
2086 @Override
2087 public boolean removeIf(Predicate<? super E> filter) {
2088 synchronized (mutex) {return c.removeIf(filter);}
2089 }
2090 @Override
2091 public Spliterator<E> spliterator() {
2092 return c.spliterator(); // Must be manually synched by user!
2093 }
2094 @Override
2095 public Stream<E> stream() {
2096 return c.stream(); // Must be manually synched by user!
2097 }
2098 @Override
2099 public Stream<E> parallelStream() {
2100 return c.parallelStream(); // Must be manually synched by user!
2101 }
2102 @java.io.Serial
2103 private void writeObject(ObjectOutputStream s) throws IOException {
2104 synchronized (mutex) {s.defaultWriteObject();}
2105 }
2106 }
2107
2108 /**
2109 * Returns a synchronized (thread-safe) set backed by the specified
2110 * set. In order to guarantee serial access, it is critical that
2111 * <strong>all</strong> access to the backing set is accomplished
2112 * through the returned set.<p>
2113 *
2114 * It is imperative that the user manually synchronize on the returned
2115 * collection when traversing it via {@link Iterator}, {@link Spliterator}
2116 * or {@link Stream}:
2117 * <pre>
2118 * Set s = Collections.synchronizedSet(new HashSet());
2119 * ...
2120 * synchronized (s) {
2121 * Iterator i = s.iterator(); // Must be in the synchronized block
2122 * while (i.hasNext())
2129 * serializable.
2130 *
2131 * @param <T> the class of the objects in the set
2132 * @param s the set to be "wrapped" in a synchronized set.
2133 * @return a synchronized view of the specified set.
2134 */
2135 public static <T> Set<T> synchronizedSet(Set<T> s) {
2136 return new SynchronizedSet<>(s);
2137 }
2138
2139 static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
2140 return new SynchronizedSet<>(s, mutex);
2141 }
2142
2143 /**
2144 * @serial include
2145 */
2146 static class SynchronizedSet<E>
2147 extends SynchronizedCollection<E>
2148 implements Set<E> {
2149 @java.io.Serial
2150 private static final long serialVersionUID = 487447009682186044L;
2151
2152 SynchronizedSet(Set<E> s) {
2153 super(s);
2154 }
2155 SynchronizedSet(Set<E> s, Object mutex) {
2156 super(s, mutex);
2157 }
2158
2159 public boolean equals(Object o) {
2160 if (this == o)
2161 return true;
2162 synchronized (mutex) {return c.equals(o);}
2163 }
2164 public int hashCode() {
2165 synchronized (mutex) {return c.hashCode();}
2166 }
2167 }
2168
2169 /**
2199 * Failure to follow this advice may result in non-deterministic behavior.
2200 *
2201 * <p>The returned sorted set will be serializable if the specified
2202 * sorted set is serializable.
2203 *
2204 * @param <T> the class of the objects in the set
2205 * @param s the sorted set to be "wrapped" in a synchronized sorted set.
2206 * @return a synchronized view of the specified sorted set.
2207 */
2208 public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
2209 return new SynchronizedSortedSet<>(s);
2210 }
2211
2212 /**
2213 * @serial include
2214 */
2215 static class SynchronizedSortedSet<E>
2216 extends SynchronizedSet<E>
2217 implements SortedSet<E>
2218 {
2219 @java.io.Serial
2220 private static final long serialVersionUID = 8695801310862127406L;
2221
2222 private final SortedSet<E> ss;
2223
2224 SynchronizedSortedSet(SortedSet<E> s) {
2225 super(s);
2226 ss = s;
2227 }
2228 SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
2229 super(s, mutex);
2230 ss = s;
2231 }
2232
2233 public Comparator<? super E> comparator() {
2234 synchronized (mutex) {return ss.comparator();}
2235 }
2236
2237 public SortedSet<E> subSet(E fromElement, E toElement) {
2238 synchronized (mutex) {
2239 return new SynchronizedSortedSet<>(
2294 * <p>The returned navigable set will be serializable if the specified
2295 * navigable set is serializable.
2296 *
2297 * @param <T> the class of the objects in the set
2298 * @param s the navigable set to be "wrapped" in a synchronized navigable
2299 * set
2300 * @return a synchronized view of the specified navigable set
2301 * @since 1.8
2302 */
2303 public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) {
2304 return new SynchronizedNavigableSet<>(s);
2305 }
2306
2307 /**
2308 * @serial include
2309 */
2310 static class SynchronizedNavigableSet<E>
2311 extends SynchronizedSortedSet<E>
2312 implements NavigableSet<E>
2313 {
2314 @java.io.Serial
2315 private static final long serialVersionUID = -5505529816273629798L;
2316
2317 private final NavigableSet<E> ns;
2318
2319 SynchronizedNavigableSet(NavigableSet<E> s) {
2320 super(s);
2321 ns = s;
2322 }
2323
2324 SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) {
2325 super(s, mutex);
2326 ns = s;
2327 }
2328 public E lower(E e) { synchronized (mutex) {return ns.lower(e);} }
2329 public E floor(E e) { synchronized (mutex) {return ns.floor(e);} }
2330 public E ceiling(E e) { synchronized (mutex) {return ns.ceiling(e);} }
2331 public E higher(E e) { synchronized (mutex) {return ns.higher(e);} }
2332 public E pollFirst() { synchronized (mutex) {return ns.pollFirst();} }
2333 public E pollLast() { synchronized (mutex) {return ns.pollLast();} }
2334
2404 * @return a synchronized view of the specified list.
2405 */
2406 public static <T> List<T> synchronizedList(List<T> list) {
2407 return (list instanceof RandomAccess ?
2408 new SynchronizedRandomAccessList<>(list) :
2409 new SynchronizedList<>(list));
2410 }
2411
2412 static <T> List<T> synchronizedList(List<T> list, Object mutex) {
2413 return (list instanceof RandomAccess ?
2414 new SynchronizedRandomAccessList<>(list, mutex) :
2415 new SynchronizedList<>(list, mutex));
2416 }
2417
2418 /**
2419 * @serial include
2420 */
2421 static class SynchronizedList<E>
2422 extends SynchronizedCollection<E>
2423 implements List<E> {
2424 @java.io.Serial
2425 private static final long serialVersionUID = -7754090372962971524L;
2426
2427 final List<E> list;
2428
2429 SynchronizedList(List<E> list) {
2430 super(list);
2431 this.list = list;
2432 }
2433 SynchronizedList(List<E> list, Object mutex) {
2434 super(list, mutex);
2435 this.list = list;
2436 }
2437
2438 public boolean equals(Object o) {
2439 if (this == o)
2440 return true;
2441 synchronized (mutex) {return list.equals(o);}
2442 }
2443 public int hashCode() {
2444 synchronized (mutex) {return list.hashCode();}
2487 public void replaceAll(UnaryOperator<E> operator) {
2488 synchronized (mutex) {list.replaceAll(operator);}
2489 }
2490 @Override
2491 public void sort(Comparator<? super E> c) {
2492 synchronized (mutex) {list.sort(c);}
2493 }
2494
2495 /**
2496 * SynchronizedRandomAccessList instances are serialized as
2497 * SynchronizedList instances to allow them to be deserialized
2498 * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
2499 * This method inverts the transformation. As a beneficial
2500 * side-effect, it also grafts the RandomAccess marker onto
2501 * SynchronizedList instances that were serialized in pre-1.4 JREs.
2502 *
2503 * Note: Unfortunately, SynchronizedRandomAccessList instances
2504 * serialized in 1.4.1 and deserialized in 1.4 will become
2505 * SynchronizedList instances, as this method was missing in 1.4.
2506 */
2507 @java.io.Serial
2508 private Object readResolve() {
2509 return (list instanceof RandomAccess
2510 ? new SynchronizedRandomAccessList<>(list)
2511 : this);
2512 }
2513 }
2514
2515 /**
2516 * @serial include
2517 */
2518 static class SynchronizedRandomAccessList<E>
2519 extends SynchronizedList<E>
2520 implements RandomAccess {
2521
2522 SynchronizedRandomAccessList(List<E> list) {
2523 super(list);
2524 }
2525
2526 SynchronizedRandomAccessList(List<E> list, Object mutex) {
2527 super(list, mutex);
2528 }
2529
2530 public List<E> subList(int fromIndex, int toIndex) {
2531 synchronized (mutex) {
2532 return new SynchronizedRandomAccessList<>(
2533 list.subList(fromIndex, toIndex), mutex);
2534 }
2535 }
2536
2537 @java.io.Serial
2538 private static final long serialVersionUID = 1530674583602358482L;
2539
2540 /**
2541 * Allows instances to be deserialized in pre-1.4 JREs (which do
2542 * not have SynchronizedRandomAccessList). SynchronizedList has
2543 * a readResolve method that inverts this transformation upon
2544 * deserialization.
2545 */
2546 @java.io.Serial
2547 private Object writeReplace() {
2548 return new SynchronizedList<>(list);
2549 }
2550 }
2551
2552 /**
2553 * Returns a synchronized (thread-safe) map backed by the specified
2554 * map. In order to guarantee serial access, it is critical that
2555 * <strong>all</strong> access to the backing map is accomplished
2556 * through the returned map.<p>
2557 *
2558 * It is imperative that the user manually synchronize on the returned
2559 * map when traversing any of its collection views via {@link Iterator},
2560 * {@link Spliterator} or {@link Stream}:
2561 * <pre>
2562 * Map m = Collections.synchronizedMap(new HashMap());
2563 * ...
2564 * Set s = m.keySet(); // Needn't be in synchronized block
2565 * ...
2566 * synchronized (m) { // Synchronizing on m, not s!
2571 * </pre>
2572 * Failure to follow this advice may result in non-deterministic behavior.
2573 *
2574 * <p>The returned map will be serializable if the specified map is
2575 * serializable.
2576 *
2577 * @param <K> the class of the map keys
2578 * @param <V> the class of the map values
2579 * @param m the map to be "wrapped" in a synchronized map.
2580 * @return a synchronized view of the specified map.
2581 */
2582 public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
2583 return new SynchronizedMap<>(m);
2584 }
2585
2586 /**
2587 * @serial include
2588 */
2589 private static class SynchronizedMap<K,V>
2590 implements Map<K,V>, Serializable {
2591 @java.io.Serial
2592 private static final long serialVersionUID = 1978198479659022715L;
2593
2594 private final Map<K,V> m; // Backing Map
2595 final Object mutex; // Object on which to synchronize
2596
2597 SynchronizedMap(Map<K,V> m) {
2598 this.m = Objects.requireNonNull(m);
2599 mutex = this;
2600 }
2601
2602 SynchronizedMap(Map<K,V> m, Object mutex) {
2603 this.m = m;
2604 this.mutex = mutex;
2605 }
2606
2607 public int size() {
2608 synchronized (mutex) {return m.size();}
2609 }
2610 public boolean isEmpty() {
2611 synchronized (mutex) {return m.isEmpty();}
2706 public V computeIfAbsent(K key,
2707 Function<? super K, ? extends V> mappingFunction) {
2708 synchronized (mutex) {return m.computeIfAbsent(key, mappingFunction);}
2709 }
2710 @Override
2711 public V computeIfPresent(K key,
2712 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2713 synchronized (mutex) {return m.computeIfPresent(key, remappingFunction);}
2714 }
2715 @Override
2716 public V compute(K key,
2717 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2718 synchronized (mutex) {return m.compute(key, remappingFunction);}
2719 }
2720 @Override
2721 public V merge(K key, V value,
2722 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2723 synchronized (mutex) {return m.merge(key, value, remappingFunction);}
2724 }
2725
2726 @java.io.Serial
2727 private void writeObject(ObjectOutputStream s) throws IOException {
2728 synchronized (mutex) {s.defaultWriteObject();}
2729 }
2730 }
2731
2732 /**
2733 * Returns a synchronized (thread-safe) sorted map backed by the specified
2734 * sorted map. In order to guarantee serial access, it is critical that
2735 * <strong>all</strong> access to the backing sorted map is accomplished
2736 * through the returned sorted map (or its views).<p>
2737 *
2738 * It is imperative that the user manually synchronize on the returned
2739 * sorted map when traversing any of its collection views, or the
2740 * collections views of any of its {@code subMap}, {@code headMap} or
2741 * {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or
2742 * {@link Stream}:
2743 * <pre>
2744 * SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2745 * ...
2746 * Set s = m.keySet(); // Needn't be in synchronized block
2768 *
2769 * <p>The returned sorted map will be serializable if the specified
2770 * sorted map is serializable.
2771 *
2772 * @param <K> the class of the map keys
2773 * @param <V> the class of the map values
2774 * @param m the sorted map to be "wrapped" in a synchronized sorted map.
2775 * @return a synchronized view of the specified sorted map.
2776 */
2777 public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
2778 return new SynchronizedSortedMap<>(m);
2779 }
2780
2781 /**
2782 * @serial include
2783 */
2784 static class SynchronizedSortedMap<K,V>
2785 extends SynchronizedMap<K,V>
2786 implements SortedMap<K,V>
2787 {
2788 @java.io.Serial
2789 private static final long serialVersionUID = -8798146769416483793L;
2790
2791 private final SortedMap<K,V> sm;
2792
2793 SynchronizedSortedMap(SortedMap<K,V> m) {
2794 super(m);
2795 sm = m;
2796 }
2797 SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
2798 super(m, mutex);
2799 sm = m;
2800 }
2801
2802 public Comparator<? super K> comparator() {
2803 synchronized (mutex) {return sm.comparator();}
2804 }
2805
2806 public SortedMap<K,V> subMap(K fromKey, K toKey) {
2807 synchronized (mutex) {
2808 return new SynchronizedSortedMap<>(
2871 * @param <K> the class of the map keys
2872 * @param <V> the class of the map values
2873 * @param m the navigable map to be "wrapped" in a synchronized navigable
2874 * map
2875 * @return a synchronized view of the specified navigable map.
2876 * @since 1.8
2877 */
2878 public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) {
2879 return new SynchronizedNavigableMap<>(m);
2880 }
2881
2882 /**
2883 * A synchronized NavigableMap.
2884 *
2885 * @serial include
2886 */
2887 static class SynchronizedNavigableMap<K,V>
2888 extends SynchronizedSortedMap<K,V>
2889 implements NavigableMap<K,V>
2890 {
2891 @java.io.Serial
2892 private static final long serialVersionUID = 699392247599746807L;
2893
2894 private final NavigableMap<K,V> nm;
2895
2896 SynchronizedNavigableMap(NavigableMap<K,V> m) {
2897 super(m);
2898 nm = m;
2899 }
2900 SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) {
2901 super(m, mutex);
2902 nm = m;
2903 }
2904
2905 public Entry<K, V> lowerEntry(K key)
2906 { synchronized (mutex) { return nm.lowerEntry(key); } }
2907 public K lowerKey(K key)
2908 { synchronized (mutex) { return nm.lowerKey(key); } }
2909 public Entry<K, V> floorEntry(K key)
2910 { synchronized (mutex) { return nm.floorEntry(key); } }
2911 public K floorKey(K key)
3050 * @param c the collection for which a dynamically typesafe view is to be
3051 * returned
3052 * @param type the type of element that {@code c} is permitted to hold
3053 * @return a dynamically typesafe view of the specified collection
3054 * @since 1.5
3055 */
3056 public static <E> Collection<E> checkedCollection(Collection<E> c,
3057 Class<E> type) {
3058 return new CheckedCollection<>(c, type);
3059 }
3060
3061 @SuppressWarnings("unchecked")
3062 static <T> T[] zeroLengthArray(Class<T> type) {
3063 return (T[]) Array.newInstance(type, 0);
3064 }
3065
3066 /**
3067 * @serial include
3068 */
3069 static class CheckedCollection<E> implements Collection<E>, Serializable {
3070 @java.io.Serial
3071 private static final long serialVersionUID = 1578914078182001775L;
3072
3073 final Collection<E> c;
3074 final Class<E> type;
3075
3076 @SuppressWarnings("unchecked")
3077 E typeCheck(Object o) {
3078 if (o != null && !type.isInstance(o))
3079 throw new ClassCastException(badElementMsg(o));
3080 return (E) o;
3081 }
3082
3083 private String badElementMsg(Object o) {
3084 return "Attempt to insert " + o.getClass() +
3085 " element into collection with element type " + type;
3086 }
3087
3088 CheckedCollection(Collection<E> c, Class<E> type) {
3089 this.c = Objects.requireNonNull(c, "c");
3090 this.type = Objects.requireNonNull(type, "type");
3200 * whenever the backing queue does.
3201 *
3202 * @param <E> the class of the objects in the queue
3203 * @param queue the queue for which a dynamically typesafe view is to be
3204 * returned
3205 * @param type the type of element that {@code queue} is permitted to hold
3206 * @return a dynamically typesafe view of the specified queue
3207 * @since 1.8
3208 */
3209 public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type) {
3210 return new CheckedQueue<>(queue, type);
3211 }
3212
3213 /**
3214 * @serial include
3215 */
3216 static class CheckedQueue<E>
3217 extends CheckedCollection<E>
3218 implements Queue<E>, Serializable
3219 {
3220 @java.io.Serial
3221 private static final long serialVersionUID = 1433151992604707767L;
3222 final Queue<E> queue;
3223
3224 CheckedQueue(Queue<E> queue, Class<E> elementType) {
3225 super(queue, elementType);
3226 this.queue = queue;
3227 }
3228
3229 public E element() {return queue.element();}
3230 public boolean equals(Object o) {return o == this || c.equals(o);}
3231 public int hashCode() {return c.hashCode();}
3232 public E peek() {return queue.peek();}
3233 public E poll() {return queue.poll();}
3234 public E remove() {return queue.remove();}
3235 public boolean offer(E e) {return queue.offer(typeCheck(e));}
3236 }
3237
3238 /**
3239 * Returns a dynamically typesafe view of the specified set.
3240 * Any attempt to insert an element of the wrong type will result in
3255 * type, the returned set permits insertion of null elements whenever
3256 * the backing set does.
3257 *
3258 * @param <E> the class of the objects in the set
3259 * @param s the set for which a dynamically typesafe view is to be
3260 * returned
3261 * @param type the type of element that {@code s} is permitted to hold
3262 * @return a dynamically typesafe view of the specified set
3263 * @since 1.5
3264 */
3265 public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
3266 return new CheckedSet<>(s, type);
3267 }
3268
3269 /**
3270 * @serial include
3271 */
3272 static class CheckedSet<E> extends CheckedCollection<E>
3273 implements Set<E>, Serializable
3274 {
3275 @java.io.Serial
3276 private static final long serialVersionUID = 4694047833775013803L;
3277
3278 CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
3279
3280 public boolean equals(Object o) { return o == this || c.equals(o); }
3281 public int hashCode() { return c.hashCode(); }
3282 }
3283
3284 /**
3285 * Returns a dynamically typesafe view of the specified sorted set.
3286 * Any attempt to insert an element of the wrong type will result in an
3287 * immediate {@link ClassCastException}. Assuming a sorted set
3288 * contains no incorrectly typed elements prior to the time a
3289 * dynamically typesafe view is generated, and that all subsequent
3290 * access to the sorted set takes place through the view, it is
3291 * <i>guaranteed</i> that the sorted set cannot contain an incorrectly
3292 * typed element.
3293 *
3294 * <p>A discussion of the use of dynamically typesafe views may be
3295 * found in the documentation for the {@link #checkedCollection
3303 * whenever the backing sorted set does.
3304 *
3305 * @param <E> the class of the objects in the set
3306 * @param s the sorted set for which a dynamically typesafe view is to be
3307 * returned
3308 * @param type the type of element that {@code s} is permitted to hold
3309 * @return a dynamically typesafe view of the specified sorted set
3310 * @since 1.5
3311 */
3312 public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
3313 Class<E> type) {
3314 return new CheckedSortedSet<>(s, type);
3315 }
3316
3317 /**
3318 * @serial include
3319 */
3320 static class CheckedSortedSet<E> extends CheckedSet<E>
3321 implements SortedSet<E>, Serializable
3322 {
3323 @java.io.Serial
3324 private static final long serialVersionUID = 1599911165492914959L;
3325
3326 private final SortedSet<E> ss;
3327
3328 CheckedSortedSet(SortedSet<E> s, Class<E> type) {
3329 super(s, type);
3330 ss = s;
3331 }
3332
3333 public Comparator<? super E> comparator() { return ss.comparator(); }
3334 public E first() { return ss.first(); }
3335 public E last() { return ss.last(); }
3336
3337 public SortedSet<E> subSet(E fromElement, E toElement) {
3338 return checkedSortedSet(ss.subSet(fromElement,toElement), type);
3339 }
3340 public SortedSet<E> headSet(E toElement) {
3341 return checkedSortedSet(ss.headSet(toElement), type);
3342 }
3343 public SortedSet<E> tailSet(E fromElement) {
3367 * whenever the backing sorted set does.
3368 *
3369 * @param <E> the class of the objects in the set
3370 * @param s the navigable set for which a dynamically typesafe view is to be
3371 * returned
3372 * @param type the type of element that {@code s} is permitted to hold
3373 * @return a dynamically typesafe view of the specified navigable set
3374 * @since 1.8
3375 */
3376 public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,
3377 Class<E> type) {
3378 return new CheckedNavigableSet<>(s, type);
3379 }
3380
3381 /**
3382 * @serial include
3383 */
3384 static class CheckedNavigableSet<E> extends CheckedSortedSet<E>
3385 implements NavigableSet<E>, Serializable
3386 {
3387 @java.io.Serial
3388 private static final long serialVersionUID = -5429120189805438922L;
3389
3390 private final NavigableSet<E> ns;
3391
3392 CheckedNavigableSet(NavigableSet<E> s, Class<E> type) {
3393 super(s, type);
3394 ns = s;
3395 }
3396
3397 public E lower(E e) { return ns.lower(e); }
3398 public E floor(E e) { return ns.floor(e); }
3399 public E ceiling(E e) { return ns.ceiling(e); }
3400 public E higher(E e) { return ns.higher(e); }
3401 public E pollFirst() { return ns.pollFirst(); }
3402 public E pollLast() {return ns.pollLast(); }
3403 public NavigableSet<E> descendingSet()
3404 { return checkedNavigableSet(ns.descendingSet(), type); }
3405 public Iterator<E> descendingIterator()
3406 {return checkedNavigableSet(ns.descendingSet(), type).iterator(); }
3407
3451 * @param <E> the class of the objects in the list
3452 * @param list the list for which a dynamically typesafe view is to be
3453 * returned
3454 * @param type the type of element that {@code list} is permitted to hold
3455 * @return a dynamically typesafe view of the specified list
3456 * @since 1.5
3457 */
3458 public static <E> List<E> checkedList(List<E> list, Class<E> type) {
3459 return (list instanceof RandomAccess ?
3460 new CheckedRandomAccessList<>(list, type) :
3461 new CheckedList<>(list, type));
3462 }
3463
3464 /**
3465 * @serial include
3466 */
3467 static class CheckedList<E>
3468 extends CheckedCollection<E>
3469 implements List<E>
3470 {
3471 @java.io.Serial
3472 private static final long serialVersionUID = 65247728283967356L;
3473 final List<E> list;
3474
3475 CheckedList(List<E> list, Class<E> type) {
3476 super(list, type);
3477 this.list = list;
3478 }
3479
3480 public boolean equals(Object o) { return o == this || list.equals(o); }
3481 public int hashCode() { return list.hashCode(); }
3482 public E get(int index) { return list.get(index); }
3483 public E remove(int index) { return list.remove(index); }
3484 public int indexOf(Object o) { return list.indexOf(o); }
3485 public int lastIndexOf(Object o) { return list.lastIndexOf(o); }
3486
3487 public E set(int index, E element) {
3488 return list.set(index, typeCheck(element));
3489 }
3490
3491 public void add(int index, E element) {
3537 * already been replaced.
3538 */
3539 @Override
3540 public void replaceAll(UnaryOperator<E> operator) {
3541 Objects.requireNonNull(operator);
3542 list.replaceAll(e -> typeCheck(operator.apply(e)));
3543 }
3544
3545 @Override
3546 public void sort(Comparator<? super E> c) {
3547 list.sort(c);
3548 }
3549 }
3550
3551 /**
3552 * @serial include
3553 */
3554 static class CheckedRandomAccessList<E> extends CheckedList<E>
3555 implements RandomAccess
3556 {
3557 @java.io.Serial
3558 private static final long serialVersionUID = 1638200125423088369L;
3559
3560 CheckedRandomAccessList(List<E> list, Class<E> type) {
3561 super(list, type);
3562 }
3563
3564 public List<E> subList(int fromIndex, int toIndex) {
3565 return new CheckedRandomAccessList<>(
3566 list.subList(fromIndex, toIndex), type);
3567 }
3568 }
3569
3570 /**
3571 * Returns a dynamically typesafe view of the specified map.
3572 * Any attempt to insert a mapping whose key or value have the wrong
3573 * type will result in an immediate {@link ClassCastException}.
3574 * Similarly, any attempt to modify the value currently associated with
3575 * a key will result in an immediate {@link ClassCastException},
3576 * whether the modification is attempted directly through the map
3577 * itself, or through a {@link Map.Entry} instance obtained from the
3599 * @param m the map for which a dynamically typesafe view is to be
3600 * returned
3601 * @param keyType the type of key that {@code m} is permitted to hold
3602 * @param valueType the type of value that {@code m} is permitted to hold
3603 * @return a dynamically typesafe view of the specified map
3604 * @since 1.5
3605 */
3606 public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
3607 Class<K> keyType,
3608 Class<V> valueType) {
3609 return new CheckedMap<>(m, keyType, valueType);
3610 }
3611
3612
3613 /**
3614 * @serial include
3615 */
3616 private static class CheckedMap<K,V>
3617 implements Map<K,V>, Serializable
3618 {
3619 @java.io.Serial
3620 private static final long serialVersionUID = 5742860141034234728L;
3621
3622 private final Map<K, V> m;
3623 final Class<K> keyType;
3624 final Class<V> valueType;
3625
3626 private void typeCheck(Object key, Object value) {
3627 if (key != null && !keyType.isInstance(key))
3628 throw new ClassCastException(badKeyMsg(key));
3629
3630 if (value != null && !valueType.isInstance(value))
3631 throw new ClassCastException(badValueMsg(value));
3632 }
3633
3634 private BiFunction<? super K, ? super V, ? extends V> typeCheck(
3635 BiFunction<? super K, ? super V, ? extends V> func) {
3636 Objects.requireNonNull(func);
3637 return (k, v) -> {
3638 V newValue = func.apply(k, v);
3639 typeCheck(k, newValue);
3999 * @param <V> the class of the map values
4000 * @param m the map for which a dynamically typesafe view is to be
4001 * returned
4002 * @param keyType the type of key that {@code m} is permitted to hold
4003 * @param valueType the type of value that {@code m} is permitted to hold
4004 * @return a dynamically typesafe view of the specified map
4005 * @since 1.5
4006 */
4007 public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
4008 Class<K> keyType,
4009 Class<V> valueType) {
4010 return new CheckedSortedMap<>(m, keyType, valueType);
4011 }
4012
4013 /**
4014 * @serial include
4015 */
4016 static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
4017 implements SortedMap<K,V>, Serializable
4018 {
4019 @java.io.Serial
4020 private static final long serialVersionUID = 1599671320688067438L;
4021
4022 private final SortedMap<K, V> sm;
4023
4024 CheckedSortedMap(SortedMap<K, V> m,
4025 Class<K> keyType, Class<V> valueType) {
4026 super(m, keyType, valueType);
4027 sm = m;
4028 }
4029
4030 public Comparator<? super K> comparator() { return sm.comparator(); }
4031 public K firstKey() { return sm.firstKey(); }
4032 public K lastKey() { return sm.lastKey(); }
4033
4034 public SortedMap<K,V> subMap(K fromKey, K toKey) {
4035 return checkedSortedMap(sm.subMap(fromKey, toKey),
4036 keyType, valueType);
4037 }
4038 public SortedMap<K,V> headMap(K toKey) {
4039 return checkedSortedMap(sm.headMap(toKey), keyType, valueType);
4074 * @param <V> type of map values
4075 * @param m the map for which a dynamically typesafe view is to be
4076 * returned
4077 * @param keyType the type of key that {@code m} is permitted to hold
4078 * @param valueType the type of value that {@code m} is permitted to hold
4079 * @return a dynamically typesafe view of the specified map
4080 * @since 1.8
4081 */
4082 public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m,
4083 Class<K> keyType,
4084 Class<V> valueType) {
4085 return new CheckedNavigableMap<>(m, keyType, valueType);
4086 }
4087
4088 /**
4089 * @serial include
4090 */
4091 static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V>
4092 implements NavigableMap<K,V>, Serializable
4093 {
4094 @java.io.Serial
4095 private static final long serialVersionUID = -4852462692372534096L;
4096
4097 private final NavigableMap<K, V> nm;
4098
4099 CheckedNavigableMap(NavigableMap<K, V> m,
4100 Class<K> keyType, Class<V> valueType) {
4101 super(m, keyType, valueType);
4102 nm = m;
4103 }
4104
4105 public Comparator<? super K> comparator() { return nm.comparator(); }
4106 public K firstKey() { return nm.firstKey(); }
4107 public K lastKey() { return nm.lastKey(); }
4108
4109 public Entry<K, V> lowerEntry(K key) {
4110 Entry<K,V> lower = nm.lowerEntry(key);
4111 return (null != lower)
4112 ? new CheckedMap.CheckedEntrySet.CheckedEntry<>(lower, valueType)
4113 : null;
4114 }
4353 * field does not provide type safety.)
4354 *
4355 * @param <T> the class of the objects in the set
4356 * @return the empty set
4357 *
4358 * @see #EMPTY_SET
4359 * @since 1.5
4360 */
4361 @SuppressWarnings("unchecked")
4362 public static final <T> Set<T> emptySet() {
4363 return (Set<T>) EMPTY_SET;
4364 }
4365
4366 /**
4367 * @serial include
4368 */
4369 private static class EmptySet<E>
4370 extends AbstractSet<E>
4371 implements Serializable
4372 {
4373 @java.io.Serial
4374 private static final long serialVersionUID = 1582296315990362920L;
4375
4376 public Iterator<E> iterator() { return emptyIterator(); }
4377
4378 public int size() {return 0;}
4379 public boolean isEmpty() {return true;}
4380 public void clear() {}
4381
4382 public boolean contains(Object obj) {return false;}
4383 public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
4384
4385 public Object[] toArray() { return new Object[0]; }
4386
4387 public <T> T[] toArray(T[] a) {
4388 if (a.length > 0)
4389 a[0] = null;
4390 return a;
4391 }
4392
4393 // Override default methods in Collection
4394 @Override
4395 public void forEach(Consumer<? super E> action) {
4396 Objects.requireNonNull(action);
4397 }
4398 @Override
4399 public boolean removeIf(Predicate<? super E> filter) {
4400 Objects.requireNonNull(filter);
4401 return false;
4402 }
4403 @Override
4404 public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4405
4406 // Preserves singleton property
4407 @java.io.Serial
4408 private Object readResolve() {
4409 return EMPTY_SET;
4410 }
4411
4412 @Override
4413 public int hashCode() {
4414 return 0;
4415 }
4416 }
4417
4418 /**
4419 * Returns an empty sorted set (immutable). This set is serializable.
4420 *
4421 * <p>This example illustrates the type-safe way to obtain an empty
4422 * sorted set:
4423 * <pre> {@code
4424 * SortedSet<String> s = Collections.emptySortedSet();
4425 * }</pre>
4426 *
4427 * @implNote Implementations of this method need not create a separate
4479 * cost to using the like-named field. (Unlike this method, the field does
4480 * not provide type safety.)
4481 *
4482 * @param <T> type of elements, if there were any, in the list
4483 * @return an empty immutable list
4484 *
4485 * @see #EMPTY_LIST
4486 * @since 1.5
4487 */
4488 @SuppressWarnings("unchecked")
4489 public static final <T> List<T> emptyList() {
4490 return (List<T>) EMPTY_LIST;
4491 }
4492
4493 /**
4494 * @serial include
4495 */
4496 private static class EmptyList<E>
4497 extends AbstractList<E>
4498 implements RandomAccess, Serializable {
4499 @java.io.Serial
4500 private static final long serialVersionUID = 8842843931221139166L;
4501
4502 public Iterator<E> iterator() {
4503 return emptyIterator();
4504 }
4505 public ListIterator<E> listIterator() {
4506 return emptyListIterator();
4507 }
4508
4509 public int size() {return 0;}
4510 public boolean isEmpty() {return true;}
4511 public void clear() {}
4512
4513 public boolean contains(Object obj) {return false;}
4514 public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
4515
4516 public Object[] toArray() { return new Object[0]; }
4517
4518 public <T> T[] toArray(T[] a) {
4519 if (a.length > 0)
4537 return false;
4538 }
4539 @Override
4540 public void replaceAll(UnaryOperator<E> operator) {
4541 Objects.requireNonNull(operator);
4542 }
4543 @Override
4544 public void sort(Comparator<? super E> c) {
4545 }
4546
4547 // Override default methods in Collection
4548 @Override
4549 public void forEach(Consumer<? super E> action) {
4550 Objects.requireNonNull(action);
4551 }
4552
4553 @Override
4554 public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4555
4556 // Preserves singleton property
4557 @java.io.Serial
4558 private Object readResolve() {
4559 return EMPTY_LIST;
4560 }
4561 }
4562
4563 /**
4564 * The empty map (immutable). This map is serializable.
4565 *
4566 * @see #emptyMap()
4567 * @since 1.3
4568 */
4569 @SuppressWarnings("rawtypes")
4570 public static final Map EMPTY_MAP = new EmptyMap<>();
4571
4572 /**
4573 * Returns an empty map (immutable). This map is serializable.
4574 *
4575 * <p>This example illustrates the type-safe way to obtain an empty map:
4576 * <pre>
4577 * Map<String, Date> s = Collections.emptyMap();
4624 * @implNote Implementations of this method need not create a separate
4625 * {@code NavigableMap} object for each call.
4626 *
4627 * @param <K> the class of the map keys
4628 * @param <V> the class of the map values
4629 * @return an empty navigable map
4630 * @since 1.8
4631 */
4632 @SuppressWarnings("unchecked")
4633 public static final <K,V> NavigableMap<K,V> emptyNavigableMap() {
4634 return (NavigableMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;
4635 }
4636
4637 /**
4638 * @serial include
4639 */
4640 private static class EmptyMap<K,V>
4641 extends AbstractMap<K,V>
4642 implements Serializable
4643 {
4644 @java.io.Serial
4645 private static final long serialVersionUID = 6428348081105594320L;
4646
4647 public int size() {return 0;}
4648 public boolean isEmpty() {return true;}
4649 public void clear() {}
4650 public boolean containsKey(Object key) {return false;}
4651 public boolean containsValue(Object value) {return false;}
4652 public V get(Object key) {return null;}
4653 public Set<K> keySet() {return emptySet();}
4654 public Collection<V> values() {return emptySet();}
4655 public Set<Map.Entry<K,V>> entrySet() {return emptySet();}
4656
4657 public boolean equals(Object o) {
4658 return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
4659 }
4660
4661 public int hashCode() {return 0;}
4662
4663 // Override default methods in Map
4664 @Override
4705
4706 @Override
4707 public V computeIfPresent(K key,
4708 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4709 throw new UnsupportedOperationException();
4710 }
4711
4712 @Override
4713 public V compute(K key,
4714 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4715 throw new UnsupportedOperationException();
4716 }
4717
4718 @Override
4719 public V merge(K key, V value,
4720 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
4721 throw new UnsupportedOperationException();
4722 }
4723
4724 // Preserves singleton property
4725 @java.io.Serial
4726 private Object readResolve() {
4727 return EMPTY_MAP;
4728 }
4729 }
4730
4731 // Singleton collections
4732
4733 /**
4734 * Returns an immutable set containing only the specified object.
4735 * The returned set is serializable.
4736 *
4737 * @param <T> the class of the objects in the set
4738 * @param o the sole object to be stored in the returned set.
4739 * @return an immutable set containing only the specified object.
4740 */
4741 public static <T> Set<T> singleton(T o) {
4742 return new SingletonSet<>(o);
4743 }
4744
4745 static <E> Iterator<E> singletonIterator(final E e) {
4805 return est;
4806 }
4807
4808 @Override
4809 public int characteristics() {
4810 int value = (element != null) ? Spliterator.NONNULL : 0;
4811
4812 return value | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE |
4813 Spliterator.DISTINCT | Spliterator.ORDERED;
4814 }
4815 };
4816 }
4817
4818 /**
4819 * @serial include
4820 */
4821 private static class SingletonSet<E>
4822 extends AbstractSet<E>
4823 implements Serializable
4824 {
4825 @java.io.Serial
4826 private static final long serialVersionUID = 3193687207550431679L;
4827
4828 private final E element;
4829
4830 SingletonSet(E e) {element = e;}
4831
4832 public Iterator<E> iterator() {
4833 return singletonIterator(element);
4834 }
4835
4836 public int size() {return 1;}
4837
4838 public boolean contains(Object o) {return eq(o, element);}
4839
4840 // Override default methods for Collection
4841 @Override
4842 public void forEach(Consumer<? super E> action) {
4843 action.accept(element);
4844 }
4845 @Override
4859 /**
4860 * Returns an immutable list containing only the specified object.
4861 * The returned list is serializable.
4862 *
4863 * @param <T> the class of the objects in the list
4864 * @param o the sole object to be stored in the returned list.
4865 * @return an immutable list containing only the specified object.
4866 * @since 1.3
4867 */
4868 public static <T> List<T> singletonList(T o) {
4869 return new SingletonList<>(o);
4870 }
4871
4872 /**
4873 * @serial include
4874 */
4875 private static class SingletonList<E>
4876 extends AbstractList<E>
4877 implements RandomAccess, Serializable {
4878
4879 @java.io.Serial
4880 private static final long serialVersionUID = 3093736618740652951L;
4881
4882 private final E element;
4883
4884 SingletonList(E obj) {element = obj;}
4885
4886 public Iterator<E> iterator() {
4887 return singletonIterator(element);
4888 }
4889
4890 public int size() {return 1;}
4891
4892 public boolean contains(Object obj) {return eq(obj, element);}
4893
4894 public E get(int index) {
4895 if (index != 0)
4896 throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
4897 return element;
4898 }
4899
4928 * specified value. The returned map is serializable.
4929 *
4930 * @param <K> the class of the map keys
4931 * @param <V> the class of the map values
4932 * @param key the sole key to be stored in the returned map.
4933 * @param value the value to which the returned map maps {@code key}.
4934 * @return an immutable map containing only the specified key-value
4935 * mapping.
4936 * @since 1.3
4937 */
4938 public static <K,V> Map<K,V> singletonMap(K key, V value) {
4939 return new SingletonMap<>(key, value);
4940 }
4941
4942 /**
4943 * @serial include
4944 */
4945 private static class SingletonMap<K,V>
4946 extends AbstractMap<K,V>
4947 implements Serializable {
4948 @java.io.Serial
4949 private static final long serialVersionUID = -6979724477215052911L;
4950
4951 private final K k;
4952 private final V v;
4953
4954 SingletonMap(K key, V value) {
4955 k = key;
4956 v = value;
4957 }
4958
4959 public int size() {return 1;}
4960 public boolean isEmpty() {return false;}
4961 public boolean containsKey(Object key) {return eq(key, k);}
4962 public boolean containsValue(Object value) {return eq(value, v);}
4963 public V get(Object key) {return (eq(key, k) ? v : null);}
4964
4965 private transient Set<K> keySet;
4966 private transient Set<Map.Entry<K,V>> entrySet;
4967 private transient Collection<V> values;
4968
5066 * @param o the element to appear repeatedly in the returned list.
5067 * @return an immutable list consisting of {@code n} copies of the
5068 * specified object.
5069 * @throws IllegalArgumentException if {@code n < 0}
5070 * @see List#addAll(Collection)
5071 * @see List#addAll(int, Collection)
5072 */
5073 public static <T> List<T> nCopies(int n, T o) {
5074 if (n < 0)
5075 throw new IllegalArgumentException("List length = " + n);
5076 return new CopiesList<>(n, o);
5077 }
5078
5079 /**
5080 * @serial include
5081 */
5082 private static class CopiesList<E>
5083 extends AbstractList<E>
5084 implements RandomAccess, Serializable
5085 {
5086 @java.io.Serial
5087 private static final long serialVersionUID = 2739099268398711800L;
5088
5089 final int n;
5090 final E element;
5091
5092 CopiesList(int n, E e) {
5093 assert n >= 0;
5094 this.n = n;
5095 element = e;
5096 }
5097
5098 public int size() {
5099 return n;
5100 }
5101
5102 public boolean contains(Object obj) {
5103 return n != 0 && eq(obj, element);
5104 }
5105
5106 public int indexOf(Object o) {
5198 }
5199 return remaining == 0 && !itr.hasNext();
5200 }
5201
5202 // Override default methods in Collection
5203 @Override
5204 public Stream<E> stream() {
5205 return IntStream.range(0, n).mapToObj(i -> element);
5206 }
5207
5208 @Override
5209 public Stream<E> parallelStream() {
5210 return IntStream.range(0, n).parallel().mapToObj(i -> element);
5211 }
5212
5213 @Override
5214 public Spliterator<E> spliterator() {
5215 return stream().spliterator();
5216 }
5217
5218 @java.io.Serial
5219 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
5220 ois.defaultReadObject();
5221 SharedSecrets.getJavaObjectInputStreamAccess().checkArray(ois, Object[].class, n);
5222 }
5223 }
5224
5225 /**
5226 * Returns a comparator that imposes the reverse of the <em>natural
5227 * ordering</em> on a collection of objects that implement the
5228 * {@code Comparable} interface. (The natural ordering is the ordering
5229 * imposed by the objects' own {@code compareTo} method.) This enables a
5230 * simple idiom for sorting (or maintaining) collections (or arrays) of
5231 * objects that implement the {@code Comparable} interface in
5232 * reverse-natural-order. For example, suppose {@code a} is an array of
5233 * strings. Then: <pre>
5234 * Arrays.sort(a, Collections.reverseOrder());
5235 * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
5236 *
5237 * The returned comparator is serializable.
5238 *
5239 * @param <T> the class of the objects compared by the comparator
5240 * @return A comparator that imposes the reverse of the <i>natural
5241 * ordering</i> on a collection of objects that implement
5242 * the {@code Comparable} interface.
5243 * @see Comparable
5244 */
5245 @SuppressWarnings("unchecked")
5246 public static <T> Comparator<T> reverseOrder() {
5247 return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5248 }
5249
5250 /**
5251 * @serial include
5252 */
5253 private static class ReverseComparator
5254 implements Comparator<Comparable<Object>>, Serializable {
5255
5256 @java.io.Serial
5257 private static final long serialVersionUID = 7207038068494060240L;
5258
5259 static final ReverseComparator REVERSE_ORDER
5260 = new ReverseComparator();
5261
5262 public int compare(Comparable<Object> c1, Comparable<Object> c2) {
5263 return c2.compareTo(c1);
5264 }
5265
5266 @java.io.Serial
5267 private Object readResolve() { return Collections.reverseOrder(); }
5268
5269 @Override
5270 public Comparator<Comparable<Object>> reversed() {
5271 return Comparator.naturalOrder();
5272 }
5273 }
5274
5275 /**
5276 * Returns a comparator that imposes the reverse ordering of the specified
5277 * comparator. If the specified comparator is {@code null}, this method is
5278 * equivalent to {@link #reverseOrder()} (in other words, it returns a
5279 * comparator that imposes the reverse of the <em>natural ordering</em> on
5280 * a collection of objects that implement the Comparable interface).
5281 *
5282 * <p>The returned comparator is serializable (assuming the specified
5283 * comparator is also serializable or {@code null}).
5284 *
5285 * @param <T> the class of the objects compared by the comparator
5286 * @param cmp a comparator who's ordering is to be reversed by the returned
5293 public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
5294 if (cmp == null) {
5295 return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5296 } else if (cmp == ReverseComparator.REVERSE_ORDER) {
5297 return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;
5298 } else if (cmp == Comparators.NaturalOrderComparator.INSTANCE) {
5299 return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5300 } else if (cmp instanceof ReverseComparator2) {
5301 return ((ReverseComparator2<T>) cmp).cmp;
5302 } else {
5303 return new ReverseComparator2<>(cmp);
5304 }
5305 }
5306
5307 /**
5308 * @serial include
5309 */
5310 private static class ReverseComparator2<T> implements Comparator<T>,
5311 Serializable
5312 {
5313 @java.io.Serial
5314 private static final long serialVersionUID = 4374092139857L;
5315
5316 /**
5317 * The comparator specified in the static factory. This will never
5318 * be null, as the static factory returns a ReverseComparator
5319 * instance if its argument is null.
5320 *
5321 * @serial
5322 */
5323 final Comparator<T> cmp;
5324
5325 ReverseComparator2(Comparator<T> cmp) {
5326 assert cmp != null;
5327 this.cmp = cmp;
5328 }
5329
5330 public int compare(T t1, T t2) {
5331 return cmp.compare(t2, t1);
5332 }
5333
5628 public boolean retainAll(Collection<?> c) {return s.retainAll(c);}
5629 // addAll is the only inherited implementation
5630
5631 // Override default methods in Collection
5632 @Override
5633 public void forEach(Consumer<? super E> action) {
5634 s.forEach(action);
5635 }
5636 @Override
5637 public boolean removeIf(Predicate<? super E> filter) {
5638 return s.removeIf(filter);
5639 }
5640
5641 @Override
5642 public Spliterator<E> spliterator() {return s.spliterator();}
5643 @Override
5644 public Stream<E> stream() {return s.stream();}
5645 @Override
5646 public Stream<E> parallelStream() {return s.parallelStream();}
5647
5648 @java.io.Serial
5649 private static final long serialVersionUID = 2454657854757543876L;
5650
5651 @java.io.Serial
5652 private void readObject(java.io.ObjectInputStream stream)
5653 throws IOException, ClassNotFoundException
5654 {
5655 stream.defaultReadObject();
5656 s = m.keySet();
5657 }
5658 }
5659
5660 /**
5661 * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
5662 * {@link Queue}. Method {@code add} is mapped to {@code push},
5663 * {@code remove} is mapped to {@code pop} and so on. This
5664 * view can be useful when you would like to use a method
5665 * requiring a {@code Queue} but you need Lifo ordering.
5666 *
5667 * <p>Each method invocation on the queue returned by this method
5668 * results in exactly one method invocation on the backing deque, with
5669 * one exception. The {@link Queue#addAll addAll} method is
5670 * implemented as a sequence of {@link Deque#addFirst addFirst}
5671 * invocations on the backing deque.
5672 *
5673 * @param <T> the class of the objects in the deque
5674 * @param deque the deque
5675 * @return the queue
5676 * @since 1.6
5677 */
5678 public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
5679 return new AsLIFOQueue<>(Objects.requireNonNull(deque));
5680 }
5681
5682 /**
5683 * @serial include
5684 */
5685 static class AsLIFOQueue<E> extends AbstractQueue<E>
5686 implements Queue<E>, Serializable {
5687 @java.io.Serial
5688 private static final long serialVersionUID = 1802017725587941708L;
5689 private final Deque<E> q;
5690 AsLIFOQueue(Deque<E> q) { this.q = q; }
5691 public boolean add(E e) { q.addFirst(e); return true; }
5692 public boolean offer(E e) { return q.offerFirst(e); }
5693 public E poll() { return q.pollFirst(); }
5694 public E remove() { return q.removeFirst(); }
5695 public E peek() { return q.peekFirst(); }
5696 public E element() { return q.getFirst(); }
5697 public void clear() { q.clear(); }
5698 public int size() { return q.size(); }
5699 public boolean isEmpty() { return q.isEmpty(); }
5700 public boolean contains(Object o) { return q.contains(o); }
5701 public boolean remove(Object o) { return q.remove(o); }
5702 public Iterator<E> iterator() { return q.iterator(); }
5703 public Object[] toArray() { return q.toArray(); }
5704 public <T> T[] toArray(T[] a) { return q.toArray(a); }
5705 public <T> T[] toArray(IntFunction<T[]> f) { return q.toArray(f); }
5706 public String toString() { return q.toString(); }
5707 public boolean containsAll(Collection<?> c) { return q.containsAll(c); }
|