Path: blob/master/src/java.base/share/classes/java/util/Collections.java
41152 views
/*1* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.util;2627import java.io.IOException;28import java.io.ObjectInputStream;29import java.io.ObjectOutputStream;30import java.io.Serializable;31import java.lang.reflect.Array;32import java.util.function.BiConsumer;33import java.util.function.BiFunction;34import java.util.function.Consumer;35import java.util.function.Function;36import java.util.function.IntFunction;37import java.util.function.Predicate;38import java.util.function.UnaryOperator;39import java.util.stream.IntStream;40import java.util.stream.Stream;41import java.util.stream.StreamSupport;42import jdk.internal.access.SharedSecrets;4344/**45* This class consists exclusively of static methods that operate on or return46* collections. It contains polymorphic algorithms that operate on47* collections, "wrappers", which return a new collection backed by a48* specified collection, and a few other odds and ends.49*50* <p>The methods of this class all throw a {@code NullPointerException}51* if the collections or class objects provided to them are null.52*53* <p>The documentation for the polymorphic algorithms contained in this class54* generally includes a brief description of the <i>implementation</i>. Such55* descriptions should be regarded as <i>implementation notes</i>, rather than56* parts of the <i>specification</i>. Implementors should feel free to57* substitute other algorithms, so long as the specification itself is adhered58* to. (For example, the algorithm used by {@code sort} does not have to be59* a mergesort, but it does have to be <i>stable</i>.)60*61* <p>The "destructive" algorithms contained in this class, that is, the62* algorithms that modify the collection on which they operate, are specified63* to throw {@code UnsupportedOperationException} if the collection does not64* support the appropriate mutation primitive(s), such as the {@code set}65* method. These algorithms may, but are not required to, throw this66* exception if an invocation would have no effect on the collection. For67* example, invoking the {@code sort} method on an unmodifiable list that is68* already sorted may or may not throw {@code UnsupportedOperationException}.69*70* <p>This class is a member of the71* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">72* Java Collections Framework</a>.73*74* @author Josh Bloch75* @author Neal Gafter76* @see Collection77* @see Set78* @see List79* @see Map80* @since 1.281*/8283public class Collections {84// Suppresses default constructor, ensuring non-instantiability.85private Collections() {86}8788// Algorithms8990/*91* Tuning parameters for algorithms - Many of the List algorithms have92* two implementations, one of which is appropriate for RandomAccess93* lists, the other for "sequential." Often, the random access variant94* yields better performance on small sequential access lists. The95* tuning parameters below determine the cutoff point for what constitutes96* a "small" sequential access list for each algorithm. The values below97* were empirically determined to work well for LinkedList. Hopefully98* they should be reasonable for other sequential access List99* implementations. Those doing performance work on this code would100* do well to validate the values of these parameters from time to time.101* (The first word of each tuning parameter name is the algorithm to which102* it applies.)103*/104private static final int BINARYSEARCH_THRESHOLD = 5000;105private static final int REVERSE_THRESHOLD = 18;106private static final int SHUFFLE_THRESHOLD = 5;107private static final int FILL_THRESHOLD = 25;108private static final int ROTATE_THRESHOLD = 100;109private static final int COPY_THRESHOLD = 10;110private static final int REPLACEALL_THRESHOLD = 11;111private static final int INDEXOFSUBLIST_THRESHOLD = 35;112113/**114* Sorts the specified list into ascending order, according to the115* {@linkplain Comparable natural ordering} of its elements.116* All elements in the list must implement the {@link Comparable}117* interface. Furthermore, all elements in the list must be118* <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}119* must not throw a {@code ClassCastException} for any elements120* {@code e1} and {@code e2} in the list).121*122* <p>This sort is guaranteed to be <i>stable</i>: equal elements will123* not be reordered as a result of the sort.124*125* <p>The specified list must be modifiable, but need not be resizable.126*127* @implNote128* This implementation defers to the {@link List#sort(Comparator)}129* method using the specified list and a {@code null} comparator.130*131* @param <T> the class of the objects in the list132* @param list the list to be sorted.133* @throws ClassCastException if the list contains elements that are not134* <i>mutually comparable</i> (for example, strings and integers).135* @throws UnsupportedOperationException if the specified list's136* list-iterator does not support the {@code set} operation.137* @throws IllegalArgumentException (optional) if the implementation138* detects that the natural ordering of the list elements is139* found to violate the {@link Comparable} contract140* @see List#sort(Comparator)141*/142@SuppressWarnings("unchecked")143public static <T extends Comparable<? super T>> void sort(List<T> list) {144list.sort(null);145}146147/**148* Sorts the specified list according to the order induced by the149* specified comparator. All elements in the list must be <i>mutually150* comparable</i> using the specified comparator (that is,151* {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}152* for any elements {@code e1} and {@code e2} in the list).153*154* <p>This sort is guaranteed to be <i>stable</i>: equal elements will155* not be reordered as a result of the sort.156*157* <p>The specified list must be modifiable, but need not be resizable.158*159* @implNote160* This implementation defers to the {@link List#sort(Comparator)}161* method using the specified list and comparator.162*163* @param <T> the class of the objects in the list164* @param list the list to be sorted.165* @param c the comparator to determine the order of the list. A166* {@code null} value indicates that the elements' <i>natural167* ordering</i> should be used.168* @throws ClassCastException if the list contains elements that are not169* <i>mutually comparable</i> using the specified comparator.170* @throws UnsupportedOperationException if the specified list's171* list-iterator does not support the {@code set} operation.172* @throws IllegalArgumentException (optional) if the comparator is173* found to violate the {@link Comparator} contract174* @see List#sort(Comparator)175*/176@SuppressWarnings({"unchecked", "rawtypes"})177public static <T> void sort(List<T> list, Comparator<? super T> c) {178list.sort(c);179}180181182/**183* Searches the specified list for the specified object using the binary184* search algorithm. The list must be sorted into ascending order185* according to the {@linkplain Comparable natural ordering} of its186* elements (as by the {@link #sort(List)} method) prior to making this187* call. If it is not sorted, the results are undefined. If the list188* contains multiple elements equal to the specified object, there is no189* guarantee which one will be found.190*191* <p>This method runs in log(n) time for a "random access" list (which192* provides near-constant-time positional access). If the specified list193* does not implement the {@link RandomAccess} interface and is large,194* this method will do an iterator-based binary search that performs195* O(n) link traversals and O(log n) element comparisons.196*197* @param <T> the class of the objects in the list198* @param list the list to be searched.199* @param key the key to be searched for.200* @return the index of the search key, if it is contained in the list;201* otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The202* <i>insertion point</i> is defined as the point at which the203* key would be inserted into the list: the index of the first204* element greater than the key, or {@code list.size()} if all205* elements in the list are less than the specified key. Note206* that this guarantees that the return value will be >= 0 if207* and only if the key is found.208* @throws ClassCastException if the list contains elements that are not209* <i>mutually comparable</i> (for example, strings and210* integers), or the search key is not mutually comparable211* with the elements of the list.212*/213public static <T>214int binarySearch(List<? extends Comparable<? super T>> list, T key) {215if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)216return Collections.indexedBinarySearch(list, key);217else218return Collections.iteratorBinarySearch(list, key);219}220221private static <T>222int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) {223int low = 0;224int high = list.size()-1;225226while (low <= high) {227int mid = (low + high) >>> 1;228Comparable<? super T> midVal = list.get(mid);229int cmp = midVal.compareTo(key);230231if (cmp < 0)232low = mid + 1;233else if (cmp > 0)234high = mid - 1;235else236return mid; // key found237}238return -(low + 1); // key not found239}240241private static <T>242int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key)243{244int low = 0;245int high = list.size()-1;246ListIterator<? extends Comparable<? super T>> i = list.listIterator();247248while (low <= high) {249int mid = (low + high) >>> 1;250Comparable<? super T> midVal = get(i, mid);251int cmp = midVal.compareTo(key);252253if (cmp < 0)254low = mid + 1;255else if (cmp > 0)256high = mid - 1;257else258return mid; // key found259}260return -(low + 1); // key not found261}262263/**264* Gets the ith element from the given list by repositioning the specified265* list listIterator.266*/267private static <T> T get(ListIterator<? extends T> i, int index) {268T obj = null;269int pos = i.nextIndex();270if (pos <= index) {271do {272obj = i.next();273} while (pos++ < index);274} else {275do {276obj = i.previous();277} while (--pos > index);278}279return obj;280}281282/**283* Searches the specified list for the specified object using the binary284* search algorithm. The list must be sorted into ascending order285* according to the specified comparator (as by the286* {@link #sort(List, Comparator) sort(List, Comparator)}287* method), prior to making this call. If it is288* not sorted, the results are undefined. If the list contains multiple289* elements equal to the specified object, there is no guarantee which one290* will be found.291*292* <p>This method runs in log(n) time for a "random access" list (which293* provides near-constant-time positional access). If the specified list294* does not implement the {@link RandomAccess} interface and is large,295* this method will do an iterator-based binary search that performs296* O(n) link traversals and O(log n) element comparisons.297*298* @param <T> the class of the objects in the list299* @param list the list to be searched.300* @param key the key to be searched for.301* @param c the comparator by which the list is ordered.302* A {@code null} value indicates that the elements'303* {@linkplain Comparable natural ordering} should be used.304* @return the index of the search key, if it is contained in the list;305* otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The306* <i>insertion point</i> is defined as the point at which the307* key would be inserted into the list: the index of the first308* element greater than the key, or {@code list.size()} if all309* elements in the list are less than the specified key. Note310* that this guarantees that the return value will be >= 0 if311* and only if the key is found.312* @throws ClassCastException if the list contains elements that are not313* <i>mutually comparable</i> using the specified comparator,314* or the search key is not mutually comparable with the315* elements of the list using this comparator.316*/317@SuppressWarnings("unchecked")318public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {319if (c==null)320return binarySearch((List<? extends Comparable<? super T>>) list, key);321322if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)323return Collections.indexedBinarySearch(list, key, c);324else325return Collections.iteratorBinarySearch(list, key, c);326}327328private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {329int low = 0;330int high = l.size()-1;331332while (low <= high) {333int mid = (low + high) >>> 1;334T midVal = l.get(mid);335int cmp = c.compare(midVal, key);336337if (cmp < 0)338low = mid + 1;339else if (cmp > 0)340high = mid - 1;341else342return mid; // key found343}344return -(low + 1); // key not found345}346347private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {348int low = 0;349int high = l.size()-1;350ListIterator<? extends T> i = l.listIterator();351352while (low <= high) {353int mid = (low + high) >>> 1;354T midVal = get(i, mid);355int cmp = c.compare(midVal, key);356357if (cmp < 0)358low = mid + 1;359else if (cmp > 0)360high = mid - 1;361else362return mid; // key found363}364return -(low + 1); // key not found365}366367/**368* Reverses the order of the elements in the specified list.<p>369*370* This method runs in linear time.371*372* @param list the list whose elements are to be reversed.373* @throws UnsupportedOperationException if the specified list or374* its list-iterator does not support the {@code set} operation.375*/376@SuppressWarnings({"rawtypes", "unchecked"})377public static void reverse(List<?> list) {378int size = list.size();379if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {380for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)381swap(list, i, j);382} else {383// instead of using a raw type here, it's possible to capture384// the wildcard but it will require a call to a supplementary385// private method386ListIterator fwd = list.listIterator();387ListIterator rev = list.listIterator(size);388for (int i=0, mid=list.size()>>1; i<mid; i++) {389Object tmp = fwd.next();390fwd.set(rev.previous());391rev.set(tmp);392}393}394}395396/**397* Randomly permutes the specified list using a default source of398* randomness. All permutations occur with approximately equal399* likelihood.400*401* <p>The hedge "approximately" is used in the foregoing description because402* default source of randomness is only approximately an unbiased source403* of independently chosen bits. If it were a perfect source of randomly404* chosen bits, then the algorithm would choose permutations with perfect405* uniformity.406*407* <p>This implementation traverses the list backwards, from the last408* element up to the second, repeatedly swapping a randomly selected element409* into the "current position". Elements are randomly selected from the410* portion of the list that runs from the first element to the current411* position, inclusive.412*413* <p>This method runs in linear time. If the specified list does not414* implement the {@link RandomAccess} interface and is large, this415* implementation dumps the specified list into an array before shuffling416* it, and dumps the shuffled array back into the list. This avoids the417* quadratic behavior that would result from shuffling a "sequential418* access" list in place.419*420* @param list the list to be shuffled.421* @throws UnsupportedOperationException if the specified list or422* its list-iterator does not support the {@code set} operation.423*/424public static void shuffle(List<?> list) {425Random rnd = r;426if (rnd == null)427r = rnd = new Random(); // harmless race.428shuffle(list, rnd);429}430431private static Random r;432433/**434* Randomly permute the specified list using the specified source of435* randomness. All permutations occur with equal likelihood436* assuming that the source of randomness is fair.<p>437*438* This implementation traverses the list backwards, from the last element439* up to the second, repeatedly swapping a randomly selected element into440* the "current position". Elements are randomly selected from the441* portion of the list that runs from the first element to the current442* position, inclusive.<p>443*444* This method runs in linear time. If the specified list does not445* implement the {@link RandomAccess} interface and is large, this446* implementation dumps the specified list into an array before shuffling447* it, and dumps the shuffled array back into the list. This avoids the448* quadratic behavior that would result from shuffling a "sequential449* access" list in place.450*451* @param list the list to be shuffled.452* @param rnd the source of randomness to use to shuffle the list.453* @throws UnsupportedOperationException if the specified list or its454* list-iterator does not support the {@code set} operation.455*/456@SuppressWarnings({"rawtypes", "unchecked"})457public static void shuffle(List<?> list, Random rnd) {458int size = list.size();459if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {460for (int i=size; i>1; i--)461swap(list, i-1, rnd.nextInt(i));462} else {463Object[] arr = list.toArray();464465// Shuffle array466for (int i=size; i>1; i--)467swap(arr, i-1, rnd.nextInt(i));468469// Dump array back into list470// instead of using a raw type here, it's possible to capture471// the wildcard but it will require a call to a supplementary472// private method473ListIterator it = list.listIterator();474for (Object e : arr) {475it.next();476it.set(e);477}478}479}480481/**482* Swaps the elements at the specified positions in the specified list.483* (If the specified positions are equal, invoking this method leaves484* the list unchanged.)485*486* @param list The list in which to swap elements.487* @param i the index of one element to be swapped.488* @param j the index of the other element to be swapped.489* @throws IndexOutOfBoundsException if either {@code i} or {@code j}490* is out of range (i < 0 || i >= list.size()491* || j < 0 || j >= list.size()).492* @since 1.4493*/494@SuppressWarnings({"rawtypes", "unchecked"})495public static void swap(List<?> list, int i, int j) {496// instead of using a raw type here, it's possible to capture497// the wildcard but it will require a call to a supplementary498// private method499final List l = list;500l.set(i, l.set(j, l.get(i)));501}502503/**504* Swaps the two specified elements in the specified array.505*/506private static void swap(Object[] arr, int i, int j) {507Object tmp = arr[i];508arr[i] = arr[j];509arr[j] = tmp;510}511512/**513* Replaces all of the elements of the specified list with the specified514* element. <p>515*516* This method runs in linear time.517*518* @param <T> the class of the objects in the list519* @param list the list to be filled with the specified element.520* @param obj The element with which to fill the specified list.521* @throws UnsupportedOperationException if the specified list or its522* list-iterator does not support the {@code set} operation.523*/524public static <T> void fill(List<? super T> list, T obj) {525int size = list.size();526527if (size < FILL_THRESHOLD || list instanceof RandomAccess) {528for (int i=0; i<size; i++)529list.set(i, obj);530} else {531ListIterator<? super T> itr = list.listIterator();532for (int i=0; i<size; i++) {533itr.next();534itr.set(obj);535}536}537}538539/**540* Copies all of the elements from one list into another. After the541* operation, the index of each copied element in the destination list542* will be identical to its index in the source list. The destination543* list's size must be greater than or equal to the source list's size.544* If it is greater, the remaining elements in the destination list are545* unaffected. <p>546*547* This method runs in linear time.548*549* @param <T> the class of the objects in the lists550* @param dest The destination list.551* @param src The source list.552* @throws IndexOutOfBoundsException if the destination list is too small553* to contain the entire source List.554* @throws UnsupportedOperationException if the destination list's555* list-iterator does not support the {@code set} operation.556*/557public static <T> void copy(List<? super T> dest, List<? extends T> src) {558int srcSize = src.size();559if (srcSize > dest.size())560throw new IndexOutOfBoundsException("Source does not fit in dest");561562if (srcSize < COPY_THRESHOLD ||563(src instanceof RandomAccess && dest instanceof RandomAccess)) {564for (int i=0; i<srcSize; i++)565dest.set(i, src.get(i));566} else {567ListIterator<? super T> di=dest.listIterator();568ListIterator<? extends T> si=src.listIterator();569for (int i=0; i<srcSize; i++) {570di.next();571di.set(si.next());572}573}574}575576/**577* Returns the minimum element of the given collection, according to the578* <i>natural ordering</i> of its elements. All elements in the579* collection must implement the {@code Comparable} interface.580* Furthermore, all elements in the collection must be <i>mutually581* comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a582* {@code ClassCastException} for any elements {@code e1} and583* {@code e2} in the collection).<p>584*585* This method iterates over the entire collection, hence it requires586* time proportional to the size of the collection.587*588* @param <T> the class of the objects in the collection589* @param coll the collection whose minimum element is to be determined.590* @return the minimum element of the given collection, according591* to the <i>natural ordering</i> of its elements.592* @throws ClassCastException if the collection contains elements that are593* not <i>mutually comparable</i> (for example, strings and594* integers).595* @throws NoSuchElementException if the collection is empty.596* @see Comparable597*/598public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {599Iterator<? extends T> i = coll.iterator();600T candidate = i.next();601602while (i.hasNext()) {603T next = i.next();604if (next.compareTo(candidate) < 0)605candidate = next;606}607return candidate;608}609610/**611* Returns the minimum element of the given collection, according to the612* order induced by the specified comparator. All elements in the613* collection must be <i>mutually comparable</i> by the specified614* comparator (that is, {@code comp.compare(e1, e2)} must not throw a615* {@code ClassCastException} for any elements {@code e1} and616* {@code e2} in the collection).<p>617*618* This method iterates over the entire collection, hence it requires619* time proportional to the size of the collection.620*621* @param <T> the class of the objects in the collection622* @param coll the collection whose minimum element is to be determined.623* @param comp the comparator with which to determine the minimum element.624* A {@code null} value indicates that the elements' <i>natural625* ordering</i> should be used.626* @return the minimum element of the given collection, according627* to the specified comparator.628* @throws ClassCastException if the collection contains elements that are629* not <i>mutually comparable</i> using the specified comparator.630* @throws NoSuchElementException if the collection is empty.631* @see Comparable632*/633@SuppressWarnings({"unchecked", "rawtypes"})634public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {635if (comp==null)636return (T)min((Collection) coll);637638Iterator<? extends T> i = coll.iterator();639T candidate = i.next();640641while (i.hasNext()) {642T next = i.next();643if (comp.compare(next, candidate) < 0)644candidate = next;645}646return candidate;647}648649/**650* Returns the maximum element of the given collection, according to the651* <i>natural ordering</i> of its elements. All elements in the652* collection must implement the {@code Comparable} interface.653* Furthermore, all elements in the collection must be <i>mutually654* comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a655* {@code ClassCastException} for any elements {@code e1} and656* {@code e2} in the collection).<p>657*658* This method iterates over the entire collection, hence it requires659* time proportional to the size of the collection.660*661* @param <T> the class of the objects in the collection662* @param coll the collection whose maximum element is to be determined.663* @return the maximum element of the given collection, according664* to the <i>natural ordering</i> of its elements.665* @throws ClassCastException if the collection contains elements that are666* not <i>mutually comparable</i> (for example, strings and667* integers).668* @throws NoSuchElementException if the collection is empty.669* @see Comparable670*/671public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {672Iterator<? extends T> i = coll.iterator();673T candidate = i.next();674675while (i.hasNext()) {676T next = i.next();677if (next.compareTo(candidate) > 0)678candidate = next;679}680return candidate;681}682683/**684* Returns the maximum element of the given collection, according to the685* order induced by the specified comparator. All elements in the686* collection must be <i>mutually comparable</i> by the specified687* comparator (that is, {@code comp.compare(e1, e2)} must not throw a688* {@code ClassCastException} for any elements {@code e1} and689* {@code e2} in the collection).<p>690*691* This method iterates over the entire collection, hence it requires692* time proportional to the size of the collection.693*694* @param <T> the class of the objects in the collection695* @param coll the collection whose maximum element is to be determined.696* @param comp the comparator with which to determine the maximum element.697* A {@code null} value indicates that the elements' <i>natural698* ordering</i> should be used.699* @return the maximum element of the given collection, according700* to the specified comparator.701* @throws ClassCastException if the collection contains elements that are702* not <i>mutually comparable</i> using the specified comparator.703* @throws NoSuchElementException if the collection is empty.704* @see Comparable705*/706@SuppressWarnings({"unchecked", "rawtypes"})707public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {708if (comp==null)709return (T)max((Collection) coll);710711Iterator<? extends T> i = coll.iterator();712T candidate = i.next();713714while (i.hasNext()) {715T next = i.next();716if (comp.compare(next, candidate) > 0)717candidate = next;718}719return candidate;720}721722/**723* Rotates the elements in the specified list by the specified distance.724* After calling this method, the element at index {@code i} will be725* the element previously at index {@code (i - distance)} mod726* {@code list.size()}, for all values of {@code i} between {@code 0}727* and {@code list.size()-1}, inclusive. (This method has no effect on728* the size of the list.)729*730* <p>For example, suppose {@code list} comprises{@code [t, a, n, k, s]}.731* After invoking {@code Collections.rotate(list, 1)} (or732* {@code Collections.rotate(list, -4)}), {@code list} will comprise733* {@code [s, t, a, n, k]}.734*735* <p>Note that this method can usefully be applied to sublists to736* move one or more elements within a list while preserving the737* order of the remaining elements. For example, the following idiom738* moves the element at index {@code j} forward to position739* {@code k} (which must be greater than or equal to {@code j}):740* <pre>741* Collections.rotate(list.subList(j, k+1), -1);742* </pre>743* To make this concrete, suppose {@code list} comprises744* {@code [a, b, c, d, e]}. To move the element at index {@code 1}745* ({@code b}) forward two positions, perform the following invocation:746* <pre>747* Collections.rotate(l.subList(1, 4), -1);748* </pre>749* The resulting list is {@code [a, c, d, b, e]}.750*751* <p>To move more than one element forward, increase the absolute value752* of the rotation distance. To move elements backward, use a positive753* shift distance.754*755* <p>If the specified list is small or implements the {@link756* RandomAccess} interface, this implementation exchanges the first757* element into the location it should go, and then repeatedly exchanges758* the displaced element into the location it should go until a displaced759* element is swapped into the first element. If necessary, the process760* is repeated on the second and successive elements, until the rotation761* is complete. If the specified list is large and doesn't implement the762* {@code RandomAccess} interface, this implementation breaks the763* list into two sublist views around index {@code -distance mod size}.764* Then the {@link #reverse(List)} method is invoked on each sublist view,765* and finally it is invoked on the entire list. For a more complete766* description of both algorithms, see Section 2.3 of Jon Bentley's767* <i>Programming Pearls</i> (Addison-Wesley, 1986).768*769* @param list the list to be rotated.770* @param distance the distance to rotate the list. There are no771* constraints on this value; it may be zero, negative, or772* greater than {@code list.size()}.773* @throws UnsupportedOperationException if the specified list or774* its list-iterator does not support the {@code set} operation.775* @since 1.4776*/777public static void rotate(List<?> list, int distance) {778if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)779rotate1(list, distance);780else781rotate2(list, distance);782}783784private static <T> void rotate1(List<T> list, int distance) {785int size = list.size();786if (size == 0)787return;788distance = distance % size;789if (distance < 0)790distance += size;791if (distance == 0)792return;793794for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {795T displaced = list.get(cycleStart);796int i = cycleStart;797do {798i += distance;799if (i >= size)800i -= size;801displaced = list.set(i, displaced);802nMoved ++;803} while (i != cycleStart);804}805}806807private static void rotate2(List<?> list, int distance) {808int size = list.size();809if (size == 0)810return;811int mid = -distance % size;812if (mid < 0)813mid += size;814if (mid == 0)815return;816817reverse(list.subList(0, mid));818reverse(list.subList(mid, size));819reverse(list);820}821822/**823* Replaces all occurrences of one specified value in a list with another.824* More formally, replaces with {@code newVal} each element {@code e}825* in {@code list} such that826* {@code (oldVal==null ? e==null : oldVal.equals(e))}.827* (This method has no effect on the size of the list.)828*829* @param <T> the class of the objects in the list830* @param list the list in which replacement is to occur.831* @param oldVal the old value to be replaced.832* @param newVal the new value with which {@code oldVal} is to be833* replaced.834* @return {@code true} if {@code list} contained one or more elements835* {@code e} such that836* {@code (oldVal==null ? e==null : oldVal.equals(e))}.837* @throws UnsupportedOperationException if the specified list or838* its list-iterator does not support the {@code set} operation.839* @since 1.4840*/841public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {842boolean result = false;843int size = list.size();844if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {845if (oldVal==null) {846for (int i=0; i<size; i++) {847if (list.get(i)==null) {848list.set(i, newVal);849result = true;850}851}852} else {853for (int i=0; i<size; i++) {854if (oldVal.equals(list.get(i))) {855list.set(i, newVal);856result = true;857}858}859}860} else {861ListIterator<T> itr=list.listIterator();862if (oldVal==null) {863for (int i=0; i<size; i++) {864if (itr.next()==null) {865itr.set(newVal);866result = true;867}868}869} else {870for (int i=0; i<size; i++) {871if (oldVal.equals(itr.next())) {872itr.set(newVal);873result = true;874}875}876}877}878return result;879}880881/**882* Returns the starting position of the first occurrence of the specified883* target list within the specified source list, or -1 if there is no884* such occurrence. More formally, returns the lowest index {@code i}885* such that {@code source.subList(i, i+target.size()).equals(target)},886* or -1 if there is no such index. (Returns -1 if887* {@code target.size() > source.size()})888*889* <p>This implementation uses the "brute force" technique of scanning890* over the source list, looking for a match with the target at each891* location in turn.892*893* @param source the list in which to search for the first occurrence894* of {@code target}.895* @param target the list to search for as a subList of {@code source}.896* @return the starting position of the first occurrence of the specified897* target list within the specified source list, or -1 if there898* is no such occurrence.899* @since 1.4900*/901public static int indexOfSubList(List<?> source, List<?> target) {902int sourceSize = source.size();903int targetSize = target.size();904int maxCandidate = sourceSize - targetSize;905906if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||907(source instanceof RandomAccess&&target instanceof RandomAccess)) {908nextCand:909for (int candidate = 0; candidate <= maxCandidate; candidate++) {910for (int i=0, j=candidate; i<targetSize; i++, j++)911if (!eq(target.get(i), source.get(j)))912continue nextCand; // Element mismatch, try next cand913return candidate; // All elements of candidate matched target914}915} else { // Iterator version of above algorithm916ListIterator<?> si = source.listIterator();917nextCand:918for (int candidate = 0; candidate <= maxCandidate; candidate++) {919ListIterator<?> ti = target.listIterator();920for (int i=0; i<targetSize; i++) {921if (!eq(ti.next(), si.next())) {922// Back up source iterator to next candidate923for (int j=0; j<i; j++)924si.previous();925continue nextCand;926}927}928return candidate;929}930}931return -1; // No candidate matched the target932}933934/**935* Returns the starting position of the last occurrence of the specified936* target list within the specified source list, or -1 if there is no such937* occurrence. More formally, returns the highest index {@code i}938* such that {@code source.subList(i, i+target.size()).equals(target)},939* or -1 if there is no such index. (Returns -1 if940* {@code target.size() > source.size()})941*942* <p>This implementation uses the "brute force" technique of iterating943* over the source list, looking for a match with the target at each944* location in turn.945*946* @param source the list in which to search for the last occurrence947* of {@code target}.948* @param target the list to search for as a subList of {@code source}.949* @return the starting position of the last occurrence of the specified950* target list within the specified source list, or -1 if there951* is no such occurrence.952* @since 1.4953*/954public static int lastIndexOfSubList(List<?> source, List<?> target) {955int sourceSize = source.size();956int targetSize = target.size();957int maxCandidate = sourceSize - targetSize;958959if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||960source instanceof RandomAccess) { // Index access version961nextCand:962for (int candidate = maxCandidate; candidate >= 0; candidate--) {963for (int i=0, j=candidate; i<targetSize; i++, j++)964if (!eq(target.get(i), source.get(j)))965continue nextCand; // Element mismatch, try next cand966return candidate; // All elements of candidate matched target967}968} else { // Iterator version of above algorithm969if (maxCandidate < 0)970return -1;971ListIterator<?> si = source.listIterator(maxCandidate);972nextCand:973for (int candidate = maxCandidate; candidate >= 0; candidate--) {974ListIterator<?> ti = target.listIterator();975for (int i=0; i<targetSize; i++) {976if (!eq(ti.next(), si.next())) {977if (candidate != 0) {978// Back up source iterator to next candidate979for (int j=0; j<=i+1; j++)980si.previous();981}982continue nextCand;983}984}985return candidate;986}987}988return -1; // No candidate matched the target989}990991992// Unmodifiable Wrappers993994/**995* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the996* specified collection. Query operations on the returned collection "read through"997* to the specified collection, and attempts to modify the returned998* collection, whether direct or via its iterator, result in an999* {@code UnsupportedOperationException}.<p>1000*1001* The returned collection does <i>not</i> pass the hashCode and equals1002* operations through to the backing collection, but relies on1003* {@code Object}'s {@code equals} and {@code hashCode} methods. This1004* is necessary to preserve the contracts of these operations in the case1005* that the backing collection is a set or a list.<p>1006*1007* The returned collection will be serializable if the specified collection1008* is serializable.1009*1010* @implNote This method may return its argument if the argument is already unmodifiable.1011* @param <T> the class of the objects in the collection1012* @param c the collection for which an unmodifiable view is to be1013* returned.1014* @return an unmodifiable view of the specified collection.1015*/1016@SuppressWarnings("unchecked")1017public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {1018if (c.getClass() == UnmodifiableCollection.class) {1019return (Collection<T>) c;1020}1021return new UnmodifiableCollection<>(c);1022}10231024/**1025* @serial include1026*/1027static class UnmodifiableCollection<E> implements Collection<E>, Serializable {1028@java.io.Serial1029private static final long serialVersionUID = 1820017752578914078L;10301031@SuppressWarnings("serial") // Conditionally serializable1032final Collection<? extends E> c;10331034UnmodifiableCollection(Collection<? extends E> c) {1035if (c==null)1036throw new NullPointerException();1037this.c = c;1038}10391040public int size() {return c.size();}1041public boolean isEmpty() {return c.isEmpty();}1042public boolean contains(Object o) {return c.contains(o);}1043public Object[] toArray() {return c.toArray();}1044public <T> T[] toArray(T[] a) {return c.toArray(a);}1045public <T> T[] toArray(IntFunction<T[]> f) {return c.toArray(f);}1046public String toString() {return c.toString();}10471048public Iterator<E> iterator() {1049return new Iterator<E>() {1050private final Iterator<? extends E> i = c.iterator();10511052public boolean hasNext() {return i.hasNext();}1053public E next() {return i.next();}1054public void remove() {1055throw new UnsupportedOperationException();1056}1057@Override1058public void forEachRemaining(Consumer<? super E> action) {1059// Use backing collection version1060i.forEachRemaining(action);1061}1062};1063}10641065public boolean add(E e) {1066throw new UnsupportedOperationException();1067}1068public boolean remove(Object o) {1069throw new UnsupportedOperationException();1070}10711072public boolean containsAll(Collection<?> coll) {1073return c.containsAll(coll);1074}1075public boolean addAll(Collection<? extends E> coll) {1076throw new UnsupportedOperationException();1077}1078public boolean removeAll(Collection<?> coll) {1079throw new UnsupportedOperationException();1080}1081public boolean retainAll(Collection<?> coll) {1082throw new UnsupportedOperationException();1083}1084public void clear() {1085throw new UnsupportedOperationException();1086}10871088// Override default methods in Collection1089@Override1090public void forEach(Consumer<? super E> action) {1091c.forEach(action);1092}1093@Override1094public boolean removeIf(Predicate<? super E> filter) {1095throw new UnsupportedOperationException();1096}1097@SuppressWarnings("unchecked")1098@Override1099public Spliterator<E> spliterator() {1100return (Spliterator<E>)c.spliterator();1101}1102@SuppressWarnings("unchecked")1103@Override1104public Stream<E> stream() {1105return (Stream<E>)c.stream();1106}1107@SuppressWarnings("unchecked")1108@Override1109public Stream<E> parallelStream() {1110return (Stream<E>)c.parallelStream();1111}1112}11131114/**1115* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the1116* specified set. Query operations on the returned set "read through" to the specified1117* set, and attempts to modify the returned set, whether direct or via its1118* iterator, result in an {@code UnsupportedOperationException}.<p>1119*1120* The returned set will be serializable if the specified set1121* is serializable.1122*1123* @implNote This method may return its argument if the argument is already unmodifiable.1124* @param <T> the class of the objects in the set1125* @param s the set for which an unmodifiable view is to be returned.1126* @return an unmodifiable view of the specified set.1127*/1128@SuppressWarnings("unchecked")1129public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {1130// Not checking for subclasses because of heap pollution and information leakage.1131if (s.getClass() == UnmodifiableSet.class) {1132return (Set<T>) s;1133}1134return new UnmodifiableSet<>(s);1135}11361137/**1138* @serial include1139*/1140static class UnmodifiableSet<E> extends UnmodifiableCollection<E>1141implements Set<E>, Serializable {1142@java.io.Serial1143private static final long serialVersionUID = -9215047833775013803L;11441145UnmodifiableSet(Set<? extends E> s) {super(s);}1146public boolean equals(Object o) {return o == this || c.equals(o);}1147public int hashCode() {return c.hashCode();}1148}11491150/**1151* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the1152* specified sorted set. Query operations on the returned sorted set "read1153* through" to the specified sorted set. Attempts to modify the returned1154* sorted set, whether direct, via its iterator, or via its1155* {@code subSet}, {@code headSet}, or {@code tailSet} views, result in1156* an {@code UnsupportedOperationException}.<p>1157*1158* The returned sorted set will be serializable if the specified sorted set1159* is serializable.1160*1161* @implNote This method may return its argument if the argument is already unmodifiable.1162* @param <T> the class of the objects in the set1163* @param s the sorted set for which an unmodifiable view is to be1164* returned.1165* @return an unmodifiable view of the specified sorted set.1166*/1167public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {1168// Not checking for subclasses because of heap pollution and information leakage.1169if (s.getClass() == UnmodifiableSortedSet.class) {1170return s;1171}1172return new UnmodifiableSortedSet<>(s);1173}11741175/**1176* @serial include1177*/1178static class UnmodifiableSortedSet<E>1179extends UnmodifiableSet<E>1180implements SortedSet<E>, Serializable {1181@java.io.Serial1182private static final long serialVersionUID = -4929149591599911165L;1183@SuppressWarnings("serial") // Conditionally serializable1184private final SortedSet<E> ss;11851186UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}11871188public Comparator<? super E> comparator() {return ss.comparator();}11891190public SortedSet<E> subSet(E fromElement, E toElement) {1191return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));1192}1193public SortedSet<E> headSet(E toElement) {1194return new UnmodifiableSortedSet<>(ss.headSet(toElement));1195}1196public SortedSet<E> tailSet(E fromElement) {1197return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));1198}11991200public E first() {return ss.first();}1201public E last() {return ss.last();}1202}12031204/**1205* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the1206* specified navigable set. Query operations on the returned navigable set "read1207* through" to the specified navigable set. Attempts to modify the returned1208* navigable set, whether direct, via its iterator, or via its1209* {@code subSet}, {@code headSet}, or {@code tailSet} views, result in1210* an {@code UnsupportedOperationException}.<p>1211*1212* The returned navigable set will be serializable if the specified1213* navigable set is serializable.1214*1215* @implNote This method may return its argument if the argument is already unmodifiable.1216* @param <T> the class of the objects in the set1217* @param s the navigable set for which an unmodifiable view is to be1218* returned1219* @return an unmodifiable view of the specified navigable set1220* @since 1.81221*/1222public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) {1223if (s.getClass() == UnmodifiableNavigableSet.class) {1224return s;1225}1226return new UnmodifiableNavigableSet<>(s);1227}12281229/**1230* Wraps a navigable set and disables all of the mutative operations.1231*1232* @param <E> type of elements1233* @serial include1234*/1235static class UnmodifiableNavigableSet<E>1236extends UnmodifiableSortedSet<E>1237implements NavigableSet<E>, Serializable {12381239@java.io.Serial1240private static final long serialVersionUID = -6027448201786391929L;12411242/**1243* A singleton empty unmodifiable navigable set used for1244* {@link #emptyNavigableSet()}.1245*1246* @param <E> type of elements, if there were any, and bounds1247*/1248private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E>1249implements Serializable {1250@java.io.Serial1251private static final long serialVersionUID = -6291252904449939134L;12521253public EmptyNavigableSet() {1254super(new TreeSet<>());1255}12561257@java.io.Serial1258private Object readResolve() { return EMPTY_NAVIGABLE_SET; }1259}12601261@SuppressWarnings("rawtypes")1262private static final NavigableSet<?> EMPTY_NAVIGABLE_SET =1263new EmptyNavigableSet<>();12641265/**1266* The instance we are protecting.1267*/1268@SuppressWarnings("serial") // Conditionally serializable1269private final NavigableSet<E> ns;12701271UnmodifiableNavigableSet(NavigableSet<E> s) {super(s); ns = s;}12721273public E lower(E e) { return ns.lower(e); }1274public E floor(E e) { return ns.floor(e); }1275public E ceiling(E e) { return ns.ceiling(e); }1276public E higher(E e) { return ns.higher(e); }1277public E pollFirst() { throw new UnsupportedOperationException(); }1278public E pollLast() { throw new UnsupportedOperationException(); }1279public NavigableSet<E> descendingSet()1280{ return new UnmodifiableNavigableSet<>(ns.descendingSet()); }1281public Iterator<E> descendingIterator()1282{ return descendingSet().iterator(); }12831284public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {1285return new UnmodifiableNavigableSet<>(1286ns.subSet(fromElement, fromInclusive, toElement, toInclusive));1287}12881289public NavigableSet<E> headSet(E toElement, boolean inclusive) {1290return new UnmodifiableNavigableSet<>(1291ns.headSet(toElement, inclusive));1292}12931294public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {1295return new UnmodifiableNavigableSet<>(1296ns.tailSet(fromElement, inclusive));1297}1298}12991300/**1301* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the1302* specified list. Query operations on the returned list "read through" to the1303* specified list, and attempts to modify the returned list, whether1304* direct or via its iterator, result in an1305* {@code UnsupportedOperationException}.<p>1306*1307* The returned list will be serializable if the specified list1308* is serializable. Similarly, the returned list will implement1309* {@link RandomAccess} if the specified list does.1310*1311* @implNote This method may return its argument if the argument is already unmodifiable.1312* @param <T> the class of the objects in the list1313* @param list the list for which an unmodifiable view is to be returned.1314* @return an unmodifiable view of the specified list.1315*/1316@SuppressWarnings("unchecked")1317public static <T> List<T> unmodifiableList(List<? extends T> list) {1318if (list.getClass() == UnmodifiableList.class || list.getClass() == UnmodifiableRandomAccessList.class) {1319return (List<T>) list;1320}13211322return (list instanceof RandomAccess ?1323new UnmodifiableRandomAccessList<>(list) :1324new UnmodifiableList<>(list));1325}13261327/**1328* @serial include1329*/1330static class UnmodifiableList<E> extends UnmodifiableCollection<E>1331implements List<E> {1332@java.io.Serial1333private static final long serialVersionUID = -283967356065247728L;13341335@SuppressWarnings("serial") // Conditionally serializable1336final List<? extends E> list;13371338UnmodifiableList(List<? extends E> list) {1339super(list);1340this.list = list;1341}13421343public boolean equals(Object o) {return o == this || list.equals(o);}1344public int hashCode() {return list.hashCode();}13451346public E get(int index) {return list.get(index);}1347public E set(int index, E element) {1348throw new UnsupportedOperationException();1349}1350public void add(int index, E element) {1351throw new UnsupportedOperationException();1352}1353public E remove(int index) {1354throw new UnsupportedOperationException();1355}1356public int indexOf(Object o) {return list.indexOf(o);}1357public int lastIndexOf(Object o) {return list.lastIndexOf(o);}1358public boolean addAll(int index, Collection<? extends E> c) {1359throw new UnsupportedOperationException();1360}13611362@Override1363public void replaceAll(UnaryOperator<E> operator) {1364throw new UnsupportedOperationException();1365}1366@Override1367public void sort(Comparator<? super E> c) {1368throw new UnsupportedOperationException();1369}13701371public ListIterator<E> listIterator() {return listIterator(0);}13721373public ListIterator<E> listIterator(final int index) {1374return new ListIterator<E>() {1375private final ListIterator<? extends E> i1376= list.listIterator(index);13771378public boolean hasNext() {return i.hasNext();}1379public E next() {return i.next();}1380public boolean hasPrevious() {return i.hasPrevious();}1381public E previous() {return i.previous();}1382public int nextIndex() {return i.nextIndex();}1383public int previousIndex() {return i.previousIndex();}13841385public void remove() {1386throw new UnsupportedOperationException();1387}1388public void set(E e) {1389throw new UnsupportedOperationException();1390}1391public void add(E e) {1392throw new UnsupportedOperationException();1393}13941395@Override1396public void forEachRemaining(Consumer<? super E> action) {1397i.forEachRemaining(action);1398}1399};1400}14011402public List<E> subList(int fromIndex, int toIndex) {1403return new UnmodifiableList<>(list.subList(fromIndex, toIndex));1404}14051406/**1407* UnmodifiableRandomAccessList instances are serialized as1408* UnmodifiableList instances to allow them to be deserialized1409* in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).1410* This method inverts the transformation. As a beneficial1411* side-effect, it also grafts the RandomAccess marker onto1412* UnmodifiableList instances that were serialized in pre-1.4 JREs.1413*1414* Note: Unfortunately, UnmodifiableRandomAccessList instances1415* serialized in 1.4.1 and deserialized in 1.4 will become1416* UnmodifiableList instances, as this method was missing in 1.4.1417*/1418@java.io.Serial1419private Object readResolve() {1420return (list instanceof RandomAccess1421? new UnmodifiableRandomAccessList<>(list)1422: this);1423}1424}14251426/**1427* @serial include1428*/1429static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>1430implements RandomAccess1431{1432UnmodifiableRandomAccessList(List<? extends E> list) {1433super(list);1434}14351436public List<E> subList(int fromIndex, int toIndex) {1437return new UnmodifiableRandomAccessList<>(1438list.subList(fromIndex, toIndex));1439}14401441@java.io.Serial1442private static final long serialVersionUID = -2542308836966382001L;14431444/**1445* Allows instances to be deserialized in pre-1.4 JREs (which do1446* not have UnmodifiableRandomAccessList). UnmodifiableList has1447* a readResolve method that inverts this transformation upon1448* deserialization.1449*/1450@java.io.Serial1451private Object writeReplace() {1452return new UnmodifiableList<>(list);1453}1454}14551456/**1457* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the1458* specified map. Query operations on the returned map "read through"1459* to the specified map, and attempts to modify the returned1460* map, whether direct or via its collection views, result in an1461* {@code UnsupportedOperationException}.<p>1462*1463* The returned map will be serializable if the specified map1464* is serializable.1465*1466* @implNote This method may return its argument if the argument is already unmodifiable.1467* @param <K> the class of the map keys1468* @param <V> the class of the map values1469* @param m the map for which an unmodifiable view is to be returned.1470* @return an unmodifiable view of the specified map.1471*/1472@SuppressWarnings("unchecked")1473public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {1474// Not checking for subclasses because of heap pollution and information leakage.1475if (m.getClass() == UnmodifiableMap.class) {1476return (Map<K,V>) m;1477}1478return new UnmodifiableMap<>(m);1479}14801481/**1482* @serial include1483*/1484private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {1485@java.io.Serial1486private static final long serialVersionUID = -1034234728574286014L;14871488@SuppressWarnings("serial") // Conditionally serializable1489private final Map<? extends K, ? extends V> m;14901491UnmodifiableMap(Map<? extends K, ? extends V> m) {1492if (m==null)1493throw new NullPointerException();1494this.m = m;1495}14961497public int size() {return m.size();}1498public boolean isEmpty() {return m.isEmpty();}1499public boolean containsKey(Object key) {return m.containsKey(key);}1500public boolean containsValue(Object val) {return m.containsValue(val);}1501public V get(Object key) {return m.get(key);}15021503public V put(K key, V value) {1504throw new UnsupportedOperationException();1505}1506public V remove(Object key) {1507throw new UnsupportedOperationException();1508}1509public void putAll(Map<? extends K, ? extends V> m) {1510throw new UnsupportedOperationException();1511}1512public void clear() {1513throw new UnsupportedOperationException();1514}15151516private transient Set<K> keySet;1517private transient Set<Map.Entry<K,V>> entrySet;1518private transient Collection<V> values;15191520public Set<K> keySet() {1521if (keySet==null)1522keySet = unmodifiableSet(m.keySet());1523return keySet;1524}15251526public Set<Map.Entry<K,V>> entrySet() {1527if (entrySet==null)1528entrySet = new UnmodifiableEntrySet<>(m.entrySet());1529return entrySet;1530}15311532public Collection<V> values() {1533if (values==null)1534values = unmodifiableCollection(m.values());1535return values;1536}15371538public boolean equals(Object o) {return o == this || m.equals(o);}1539public int hashCode() {return m.hashCode();}1540public String toString() {return m.toString();}15411542// Override default methods in Map1543@Override1544@SuppressWarnings("unchecked")1545public V getOrDefault(Object k, V defaultValue) {1546// Safe cast as we don't change the value1547return ((Map<K, V>)m).getOrDefault(k, defaultValue);1548}15491550@Override1551public void forEach(BiConsumer<? super K, ? super V> action) {1552m.forEach(action);1553}15541555@Override1556public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {1557throw new UnsupportedOperationException();1558}15591560@Override1561public V putIfAbsent(K key, V value) {1562throw new UnsupportedOperationException();1563}15641565@Override1566public boolean remove(Object key, Object value) {1567throw new UnsupportedOperationException();1568}15691570@Override1571public boolean replace(K key, V oldValue, V newValue) {1572throw new UnsupportedOperationException();1573}15741575@Override1576public V replace(K key, V value) {1577throw new UnsupportedOperationException();1578}15791580@Override1581public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {1582throw new UnsupportedOperationException();1583}15841585@Override1586public V computeIfPresent(K key,1587BiFunction<? super K, ? super V, ? extends V> remappingFunction) {1588throw new UnsupportedOperationException();1589}15901591@Override1592public V compute(K key,1593BiFunction<? super K, ? super V, ? extends V> remappingFunction) {1594throw new UnsupportedOperationException();1595}15961597@Override1598public V merge(K key, V value,1599BiFunction<? super V, ? super V, ? extends V> remappingFunction) {1600throw new UnsupportedOperationException();1601}16021603/**1604* We need this class in addition to UnmodifiableSet as1605* Map.Entries themselves permit modification of the backing Map1606* via their setValue operation. This class is subtle: there are1607* many possible attacks that must be thwarted.1608*1609* @serial include1610*/1611static class UnmodifiableEntrySet<K,V>1612extends UnmodifiableSet<Map.Entry<K,V>> {1613@java.io.Serial1614private static final long serialVersionUID = 7854390611657943733L;16151616@SuppressWarnings({"unchecked", "rawtypes"})1617UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {1618// Need to cast to raw in order to work around a limitation in the type system1619super((Set)s);1620}16211622static <K, V> Consumer<Map.Entry<? extends K, ? extends V>> entryConsumer(1623Consumer<? super Entry<K, V>> action) {1624return e -> action.accept(new UnmodifiableEntry<>(e));1625}16261627public void forEach(Consumer<? super Entry<K, V>> action) {1628Objects.requireNonNull(action);1629c.forEach(entryConsumer(action));1630}16311632static final class UnmodifiableEntrySetSpliterator<K, V>1633implements Spliterator<Entry<K,V>> {1634final Spliterator<Map.Entry<K, V>> s;16351636UnmodifiableEntrySetSpliterator(Spliterator<Entry<K, V>> s) {1637this.s = s;1638}16391640@Override1641public boolean tryAdvance(Consumer<? super Entry<K, V>> action) {1642Objects.requireNonNull(action);1643return s.tryAdvance(entryConsumer(action));1644}16451646@Override1647public void forEachRemaining(Consumer<? super Entry<K, V>> action) {1648Objects.requireNonNull(action);1649s.forEachRemaining(entryConsumer(action));1650}16511652@Override1653public Spliterator<Entry<K, V>> trySplit() {1654Spliterator<Entry<K, V>> split = s.trySplit();1655return split == null1656? null1657: new UnmodifiableEntrySetSpliterator<>(split);1658}16591660@Override1661public long estimateSize() {1662return s.estimateSize();1663}16641665@Override1666public long getExactSizeIfKnown() {1667return s.getExactSizeIfKnown();1668}16691670@Override1671public int characteristics() {1672return s.characteristics();1673}16741675@Override1676public boolean hasCharacteristics(int characteristics) {1677return s.hasCharacteristics(characteristics);1678}16791680@Override1681public Comparator<? super Entry<K, V>> getComparator() {1682return s.getComparator();1683}1684}16851686@SuppressWarnings("unchecked")1687public Spliterator<Entry<K,V>> spliterator() {1688return new UnmodifiableEntrySetSpliterator<>(1689(Spliterator<Map.Entry<K, V>>) c.spliterator());1690}16911692@Override1693public Stream<Entry<K,V>> stream() {1694return StreamSupport.stream(spliterator(), false);1695}16961697@Override1698public Stream<Entry<K,V>> parallelStream() {1699return StreamSupport.stream(spliterator(), true);1700}17011702public Iterator<Map.Entry<K,V>> iterator() {1703return new Iterator<Map.Entry<K,V>>() {1704private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();17051706public boolean hasNext() {1707return i.hasNext();1708}1709public Map.Entry<K,V> next() {1710return new UnmodifiableEntry<>(i.next());1711}1712public void remove() {1713throw new UnsupportedOperationException();1714}1715public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {1716i.forEachRemaining(entryConsumer(action));1717}1718};1719}17201721@SuppressWarnings("unchecked")1722public Object[] toArray() {1723Object[] a = c.toArray();1724for (int i=0; i<a.length; i++)1725a[i] = new UnmodifiableEntry<>((Map.Entry<? extends K, ? extends V>)a[i]);1726return a;1727}17281729@SuppressWarnings("unchecked")1730public <T> T[] toArray(T[] a) {1731// We don't pass a to c.toArray, to avoid window of1732// vulnerability wherein an unscrupulous multithreaded client1733// could get his hands on raw (unwrapped) Entries from c.1734Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));17351736for (int i=0; i<arr.length; i++)1737arr[i] = new UnmodifiableEntry<>((Map.Entry<? extends K, ? extends V>)arr[i]);17381739if (arr.length > a.length)1740return (T[])arr;17411742System.arraycopy(arr, 0, a, 0, arr.length);1743if (a.length > arr.length)1744a[arr.length] = null;1745return a;1746}17471748/**1749* This method is overridden to protect the backing set against1750* an object with a nefarious equals function that senses1751* that the equality-candidate is Map.Entry and calls its1752* setValue method.1753*/1754public boolean contains(Object o) {1755if (!(o instanceof Map.Entry))1756return false;1757return c.contains(1758new UnmodifiableEntry<>((Map.Entry<?,?>) o));1759}17601761/**1762* The next two methods are overridden to protect against1763* an unscrupulous List whose contains(Object o) method senses1764* when o is a Map.Entry, and calls o.setValue.1765*/1766public boolean containsAll(Collection<?> coll) {1767for (Object e : coll) {1768if (!contains(e)) // Invokes safe contains() above1769return false;1770}1771return true;1772}1773public boolean equals(Object o) {1774if (o == this)1775return true;17761777return o instanceof Set<?> s1778&& s.size() == c.size()1779&& containsAll(s); // Invokes safe containsAll() above1780}17811782/**1783* This "wrapper class" serves two purposes: it prevents1784* the client from modifying the backing Map, by short-circuiting1785* the setValue method, and it protects the backing Map against1786* an ill-behaved Map.Entry that attempts to modify another1787* Map Entry when asked to perform an equality check.1788*/1789private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {1790private Map.Entry<? extends K, ? extends V> e;17911792UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e)1793{this.e = Objects.requireNonNull(e);}17941795public K getKey() {return e.getKey();}1796public V getValue() {return e.getValue();}1797public V setValue(V value) {1798throw new UnsupportedOperationException();1799}1800public int hashCode() {return e.hashCode();}1801public boolean equals(Object o) {1802if (this == o)1803return true;1804return o instanceof Map.Entry<?, ?> t1805&& eq(e.getKey(), t.getKey())1806&& eq(e.getValue(), t.getValue());1807}1808public String toString() {return e.toString();}1809}1810}1811}18121813/**1814* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the1815* specified sorted map. Query operations on the returned sorted map "read through"1816* to the specified sorted map. Attempts to modify the returned1817* sorted map, whether direct, via its collection views, or via its1818* {@code subMap}, {@code headMap}, or {@code tailMap} views, result in1819* an {@code UnsupportedOperationException}.<p>1820*1821* The returned sorted map will be serializable if the specified sorted map1822* is serializable.1823*1824* @implNote This method may return its argument if the argument is already unmodifiable.1825* @param <K> the class of the map keys1826* @param <V> the class of the map values1827* @param m the sorted map for which an unmodifiable view is to be1828* returned.1829* @return an unmodifiable view of the specified sorted map.1830*/1831@SuppressWarnings("unchecked")1832public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {1833// Not checking for subclasses because of heap pollution and information leakage.1834if (m.getClass() == UnmodifiableSortedMap.class) {1835return (SortedMap<K,V>) m;1836}1837return new UnmodifiableSortedMap<>(m);1838}18391840/**1841* @serial include1842*/1843static class UnmodifiableSortedMap<K,V>1844extends UnmodifiableMap<K,V>1845implements SortedMap<K,V>, Serializable {1846@java.io.Serial1847private static final long serialVersionUID = -8806743815996713206L;18481849@SuppressWarnings("serial") // Conditionally serializable1850private final SortedMap<K, ? extends V> sm;18511852UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m; }1853public Comparator<? super K> comparator() { return sm.comparator(); }1854public SortedMap<K,V> subMap(K fromKey, K toKey)1855{ return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); }1856public SortedMap<K,V> headMap(K toKey)1857{ return new UnmodifiableSortedMap<>(sm.headMap(toKey)); }1858public SortedMap<K,V> tailMap(K fromKey)1859{ return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); }1860public K firstKey() { return sm.firstKey(); }1861public K lastKey() { return sm.lastKey(); }1862}18631864/**1865* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the1866* specified navigable map. Query operations on the returned navigable map "read1867* through" to the specified navigable map. Attempts to modify the returned1868* navigable map, whether direct, via its collection views, or via its1869* {@code subMap}, {@code headMap}, or {@code tailMap} views, result in1870* an {@code UnsupportedOperationException}.<p>1871*1872* The returned navigable map will be serializable if the specified1873* navigable map is serializable.1874*1875* @implNote This method may return its argument if the argument is already unmodifiable.1876* @param <K> the class of the map keys1877* @param <V> the class of the map values1878* @param m the navigable map for which an unmodifiable view is to be1879* returned1880* @return an unmodifiable view of the specified navigable map1881* @since 1.81882*/1883@SuppressWarnings("unchecked")1884public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {1885if (m.getClass() == UnmodifiableNavigableMap.class) {1886return (NavigableMap<K,V>) m;1887}1888return new UnmodifiableNavigableMap<>(m);1889}18901891/**1892* @serial include1893*/1894static class UnmodifiableNavigableMap<K,V>1895extends UnmodifiableSortedMap<K,V>1896implements NavigableMap<K,V>, Serializable {1897@java.io.Serial1898private static final long serialVersionUID = -4858195264774772197L;18991900/**1901* A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve1902* to preserve singleton property.1903*1904* @param <K> type of keys, if there were any, and of bounds1905* @param <V> type of values, if there were any1906*/1907private static class EmptyNavigableMap<K,V> extends UnmodifiableNavigableMap<K,V>1908implements Serializable {19091910@java.io.Serial1911private static final long serialVersionUID = -2239321462712562324L;19121913EmptyNavigableMap() { super(new TreeMap<>()); }19141915@Override1916public NavigableSet<K> navigableKeySet()1917{ return emptyNavigableSet(); }19181919@java.io.Serial1920private Object readResolve() { return EMPTY_NAVIGABLE_MAP; }1921}19221923/**1924* Singleton for {@link emptyNavigableMap()} which is also immutable.1925*/1926private static final EmptyNavigableMap<?,?> EMPTY_NAVIGABLE_MAP =1927new EmptyNavigableMap<>();19281929/**1930* The instance we wrap and protect.1931*/1932@SuppressWarnings("serial") // Conditionally serializable1933private final NavigableMap<K, ? extends V> nm;19341935UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m)1936{super(m); nm = m;}19371938public K lowerKey(K key) { return nm.lowerKey(key); }1939public K floorKey(K key) { return nm.floorKey(key); }1940public K ceilingKey(K key) { return nm.ceilingKey(key); }1941public K higherKey(K key) { return nm.higherKey(key); }19421943@SuppressWarnings("unchecked")1944public Entry<K, V> lowerEntry(K key) {1945Entry<K,V> lower = (Entry<K, V>) nm.lowerEntry(key);1946return (null != lower)1947? new UnmodifiableEntrySet.UnmodifiableEntry<>(lower)1948: null;1949}19501951@SuppressWarnings("unchecked")1952public Entry<K, V> floorEntry(K key) {1953Entry<K,V> floor = (Entry<K, V>) nm.floorEntry(key);1954return (null != floor)1955? new UnmodifiableEntrySet.UnmodifiableEntry<>(floor)1956: null;1957}19581959@SuppressWarnings("unchecked")1960public Entry<K, V> ceilingEntry(K key) {1961Entry<K,V> ceiling = (Entry<K, V>) nm.ceilingEntry(key);1962return (null != ceiling)1963? new UnmodifiableEntrySet.UnmodifiableEntry<>(ceiling)1964: null;1965}196619671968@SuppressWarnings("unchecked")1969public Entry<K, V> higherEntry(K key) {1970Entry<K,V> higher = (Entry<K, V>) nm.higherEntry(key);1971return (null != higher)1972? new UnmodifiableEntrySet.UnmodifiableEntry<>(higher)1973: null;1974}19751976@SuppressWarnings("unchecked")1977public Entry<K, V> firstEntry() {1978Entry<K,V> first = (Entry<K, V>) nm.firstEntry();1979return (null != first)1980? new UnmodifiableEntrySet.UnmodifiableEntry<>(first)1981: null;1982}19831984@SuppressWarnings("unchecked")1985public Entry<K, V> lastEntry() {1986Entry<K,V> last = (Entry<K, V>) nm.lastEntry();1987return (null != last)1988? new UnmodifiableEntrySet.UnmodifiableEntry<>(last)1989: null;1990}19911992public Entry<K, V> pollFirstEntry()1993{ throw new UnsupportedOperationException(); }1994public Entry<K, V> pollLastEntry()1995{ throw new UnsupportedOperationException(); }1996public NavigableMap<K, V> descendingMap()1997{ return unmodifiableNavigableMap(nm.descendingMap()); }1998public NavigableSet<K> navigableKeySet()1999{ return unmodifiableNavigableSet(nm.navigableKeySet()); }2000public NavigableSet<K> descendingKeySet()2001{ return unmodifiableNavigableSet(nm.descendingKeySet()); }20022003public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {2004return unmodifiableNavigableMap(2005nm.subMap(fromKey, fromInclusive, toKey, toInclusive));2006}20072008public NavigableMap<K, V> headMap(K toKey, boolean inclusive)2009{ return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); }2010public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)2011{ return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); }2012}20132014// Synch Wrappers20152016/**2017* Returns a synchronized (thread-safe) collection backed by the specified2018* collection. In order to guarantee serial access, it is critical that2019* <strong>all</strong> access to the backing collection is accomplished2020* through the returned collection.<p>2021*2022* It is imperative that the user manually synchronize on the returned2023* collection when traversing it via {@link Iterator}, {@link Spliterator}2024* or {@link Stream}:2025* <pre>2026* Collection c = Collections.synchronizedCollection(myCollection);2027* ...2028* synchronized (c) {2029* Iterator i = c.iterator(); // Must be in the synchronized block2030* while (i.hasNext())2031* foo(i.next());2032* }2033* </pre>2034* Failure to follow this advice may result in non-deterministic behavior.2035*2036* <p>The returned collection does <i>not</i> pass the {@code hashCode}2037* and {@code equals} operations through to the backing collection, but2038* relies on {@code Object}'s equals and hashCode methods. This is2039* necessary to preserve the contracts of these operations in the case2040* that the backing collection is a set or a list.<p>2041*2042* The returned collection will be serializable if the specified collection2043* is serializable.2044*2045* @param <T> the class of the objects in the collection2046* @param c the collection to be "wrapped" in a synchronized collection.2047* @return a synchronized view of the specified collection.2048*/2049public static <T> Collection<T> synchronizedCollection(Collection<T> c) {2050return new SynchronizedCollection<>(c);2051}20522053static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {2054return new SynchronizedCollection<>(c, mutex);2055}20562057/**2058* @serial include2059*/2060static class SynchronizedCollection<E> implements Collection<E>, Serializable {2061@java.io.Serial2062private static final long serialVersionUID = 3053995032091335093L;20632064@SuppressWarnings("serial") // Conditionally serializable2065final Collection<E> c; // Backing Collection2066@SuppressWarnings("serial") // Conditionally serializable2067final Object mutex; // Object on which to synchronize20682069SynchronizedCollection(Collection<E> c) {2070this.c = Objects.requireNonNull(c);2071mutex = this;2072}20732074SynchronizedCollection(Collection<E> c, Object mutex) {2075this.c = Objects.requireNonNull(c);2076this.mutex = Objects.requireNonNull(mutex);2077}20782079public int size() {2080synchronized (mutex) {return c.size();}2081}2082public boolean isEmpty() {2083synchronized (mutex) {return c.isEmpty();}2084}2085public boolean contains(Object o) {2086synchronized (mutex) {return c.contains(o);}2087}2088public Object[] toArray() {2089synchronized (mutex) {return c.toArray();}2090}2091public <T> T[] toArray(T[] a) {2092synchronized (mutex) {return c.toArray(a);}2093}2094public <T> T[] toArray(IntFunction<T[]> f) {2095synchronized (mutex) {return c.toArray(f);}2096}20972098public Iterator<E> iterator() {2099return c.iterator(); // Must be manually synched by user!2100}21012102public boolean add(E e) {2103synchronized (mutex) {return c.add(e);}2104}2105public boolean remove(Object o) {2106synchronized (mutex) {return c.remove(o);}2107}21082109public boolean containsAll(Collection<?> coll) {2110synchronized (mutex) {return c.containsAll(coll);}2111}2112public boolean addAll(Collection<? extends E> coll) {2113synchronized (mutex) {return c.addAll(coll);}2114}2115public boolean removeAll(Collection<?> coll) {2116synchronized (mutex) {return c.removeAll(coll);}2117}2118public boolean retainAll(Collection<?> coll) {2119synchronized (mutex) {return c.retainAll(coll);}2120}2121public void clear() {2122synchronized (mutex) {c.clear();}2123}2124public String toString() {2125synchronized (mutex) {return c.toString();}2126}2127// Override default methods in Collection2128@Override2129public void forEach(Consumer<? super E> consumer) {2130synchronized (mutex) {c.forEach(consumer);}2131}2132@Override2133public boolean removeIf(Predicate<? super E> filter) {2134synchronized (mutex) {return c.removeIf(filter);}2135}2136@Override2137public Spliterator<E> spliterator() {2138return c.spliterator(); // Must be manually synched by user!2139}2140@Override2141public Stream<E> stream() {2142return c.stream(); // Must be manually synched by user!2143}2144@Override2145public Stream<E> parallelStream() {2146return c.parallelStream(); // Must be manually synched by user!2147}2148@java.io.Serial2149private void writeObject(ObjectOutputStream s) throws IOException {2150synchronized (mutex) {s.defaultWriteObject();}2151}2152}21532154/**2155* Returns a synchronized (thread-safe) set backed by the specified2156* set. In order to guarantee serial access, it is critical that2157* <strong>all</strong> access to the backing set is accomplished2158* through the returned set.<p>2159*2160* It is imperative that the user manually synchronize on the returned2161* collection when traversing it via {@link Iterator}, {@link Spliterator}2162* or {@link Stream}:2163* <pre>2164* Set s = Collections.synchronizedSet(new HashSet());2165* ...2166* synchronized (s) {2167* Iterator i = s.iterator(); // Must be in the synchronized block2168* while (i.hasNext())2169* foo(i.next());2170* }2171* </pre>2172* Failure to follow this advice may result in non-deterministic behavior.2173*2174* <p>The returned set will be serializable if the specified set is2175* serializable.2176*2177* @param <T> the class of the objects in the set2178* @param s the set to be "wrapped" in a synchronized set.2179* @return a synchronized view of the specified set.2180*/2181public static <T> Set<T> synchronizedSet(Set<T> s) {2182return new SynchronizedSet<>(s);2183}21842185static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {2186return new SynchronizedSet<>(s, mutex);2187}21882189/**2190* @serial include2191*/2192static class SynchronizedSet<E>2193extends SynchronizedCollection<E>2194implements Set<E> {2195@java.io.Serial2196private static final long serialVersionUID = 487447009682186044L;21972198SynchronizedSet(Set<E> s) {2199super(s);2200}2201SynchronizedSet(Set<E> s, Object mutex) {2202super(s, mutex);2203}22042205public boolean equals(Object o) {2206if (this == o)2207return true;2208synchronized (mutex) {return c.equals(o);}2209}2210public int hashCode() {2211synchronized (mutex) {return c.hashCode();}2212}2213}22142215/**2216* Returns a synchronized (thread-safe) sorted set backed by the specified2217* sorted set. In order to guarantee serial access, it is critical that2218* <strong>all</strong> access to the backing sorted set is accomplished2219* through the returned sorted set (or its views).<p>2220*2221* It is imperative that the user manually synchronize on the returned2222* sorted set when traversing it or any of its {@code subSet},2223* {@code headSet}, or {@code tailSet} views via {@link Iterator},2224* {@link Spliterator} or {@link Stream}:2225* <pre>2226* SortedSet s = Collections.synchronizedSortedSet(new TreeSet());2227* ...2228* synchronized (s) {2229* Iterator i = s.iterator(); // Must be in the synchronized block2230* while (i.hasNext())2231* foo(i.next());2232* }2233* </pre>2234* or:2235* <pre>2236* SortedSet s = Collections.synchronizedSortedSet(new TreeSet());2237* SortedSet s2 = s.headSet(foo);2238* ...2239* synchronized (s) { // Note: s, not s2!!!2240* Iterator i = s2.iterator(); // Must be in the synchronized block2241* while (i.hasNext())2242* foo(i.next());2243* }2244* </pre>2245* Failure to follow this advice may result in non-deterministic behavior.2246*2247* <p>The returned sorted set will be serializable if the specified2248* sorted set is serializable.2249*2250* @param <T> the class of the objects in the set2251* @param s the sorted set to be "wrapped" in a synchronized sorted set.2252* @return a synchronized view of the specified sorted set.2253*/2254public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {2255return new SynchronizedSortedSet<>(s);2256}22572258/**2259* @serial include2260*/2261static class SynchronizedSortedSet<E>2262extends SynchronizedSet<E>2263implements SortedSet<E>2264{2265@java.io.Serial2266private static final long serialVersionUID = 8695801310862127406L;22672268@SuppressWarnings("serial") // Conditionally serializable2269private final SortedSet<E> ss;22702271SynchronizedSortedSet(SortedSet<E> s) {2272super(s);2273ss = s;2274}2275SynchronizedSortedSet(SortedSet<E> s, Object mutex) {2276super(s, mutex);2277ss = s;2278}22792280public Comparator<? super E> comparator() {2281synchronized (mutex) {return ss.comparator();}2282}22832284public SortedSet<E> subSet(E fromElement, E toElement) {2285synchronized (mutex) {2286return new SynchronizedSortedSet<>(2287ss.subSet(fromElement, toElement), mutex);2288}2289}2290public SortedSet<E> headSet(E toElement) {2291synchronized (mutex) {2292return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);2293}2294}2295public SortedSet<E> tailSet(E fromElement) {2296synchronized (mutex) {2297return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);2298}2299}23002301public E first() {2302synchronized (mutex) {return ss.first();}2303}2304public E last() {2305synchronized (mutex) {return ss.last();}2306}2307}23082309/**2310* Returns a synchronized (thread-safe) navigable set backed by the2311* specified navigable set. In order to guarantee serial access, it is2312* critical that <strong>all</strong> access to the backing navigable set is2313* accomplished through the returned navigable set (or its views).<p>2314*2315* It is imperative that the user manually synchronize on the returned2316* navigable set when traversing it, or any of its {@code subSet},2317* {@code headSet}, or {@code tailSet} views, via {@link Iterator},2318* {@link Spliterator} or {@link Stream}:2319* <pre>2320* NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());2321* ...2322* synchronized (s) {2323* Iterator i = s.iterator(); // Must be in the synchronized block2324* while (i.hasNext())2325* foo(i.next());2326* }2327* </pre>2328* or:2329* <pre>2330* NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());2331* NavigableSet s2 = s.headSet(foo, true);2332* ...2333* synchronized (s) { // Note: s, not s2!!!2334* Iterator i = s2.iterator(); // Must be in the synchronized block2335* while (i.hasNext())2336* foo(i.next());2337* }2338* </pre>2339* Failure to follow this advice may result in non-deterministic behavior.2340*2341* <p>The returned navigable set will be serializable if the specified2342* navigable set is serializable.2343*2344* @param <T> the class of the objects in the set2345* @param s the navigable set to be "wrapped" in a synchronized navigable2346* set2347* @return a synchronized view of the specified navigable set2348* @since 1.82349*/2350public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) {2351return new SynchronizedNavigableSet<>(s);2352}23532354/**2355* @serial include2356*/2357static class SynchronizedNavigableSet<E>2358extends SynchronizedSortedSet<E>2359implements NavigableSet<E>2360{2361@java.io.Serial2362private static final long serialVersionUID = -5505529816273629798L;23632364@SuppressWarnings("serial") // Conditionally serializable2365private final NavigableSet<E> ns;23662367SynchronizedNavigableSet(NavigableSet<E> s) {2368super(s);2369ns = s;2370}23712372SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) {2373super(s, mutex);2374ns = s;2375}2376public E lower(E e) { synchronized (mutex) {return ns.lower(e);} }2377public E floor(E e) { synchronized (mutex) {return ns.floor(e);} }2378public E ceiling(E e) { synchronized (mutex) {return ns.ceiling(e);} }2379public E higher(E e) { synchronized (mutex) {return ns.higher(e);} }2380public E pollFirst() { synchronized (mutex) {return ns.pollFirst();} }2381public E pollLast() { synchronized (mutex) {return ns.pollLast();} }23822383public NavigableSet<E> descendingSet() {2384synchronized (mutex) {2385return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex);2386}2387}23882389public Iterator<E> descendingIterator()2390{ synchronized (mutex) { return descendingSet().iterator(); } }23912392public NavigableSet<E> subSet(E fromElement, E toElement) {2393synchronized (mutex) {2394return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex);2395}2396}2397public NavigableSet<E> headSet(E toElement) {2398synchronized (mutex) {2399return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex);2400}2401}2402public NavigableSet<E> tailSet(E fromElement) {2403synchronized (mutex) {2404return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, true), mutex);2405}2406}24072408public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {2409synchronized (mutex) {2410return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex);2411}2412}24132414public NavigableSet<E> headSet(E toElement, boolean inclusive) {2415synchronized (mutex) {2416return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex);2417}2418}24192420public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {2421synchronized (mutex) {2422return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive), mutex);2423}2424}2425}24262427/**2428* Returns a synchronized (thread-safe) list backed by the specified2429* list. In order to guarantee serial access, it is critical that2430* <strong>all</strong> access to the backing list is accomplished2431* through the returned list.<p>2432*2433* It is imperative that the user manually synchronize on the returned2434* list when traversing it via {@link Iterator}, {@link Spliterator}2435* or {@link Stream}:2436* <pre>2437* List list = Collections.synchronizedList(new ArrayList());2438* ...2439* synchronized (list) {2440* Iterator i = list.iterator(); // Must be in synchronized block2441* while (i.hasNext())2442* foo(i.next());2443* }2444* </pre>2445* Failure to follow this advice may result in non-deterministic behavior.2446*2447* <p>The returned list will be serializable if the specified list is2448* serializable.2449*2450* @param <T> the class of the objects in the list2451* @param list the list to be "wrapped" in a synchronized list.2452* @return a synchronized view of the specified list.2453*/2454public static <T> List<T> synchronizedList(List<T> list) {2455return (list instanceof RandomAccess ?2456new SynchronizedRandomAccessList<>(list) :2457new SynchronizedList<>(list));2458}24592460static <T> List<T> synchronizedList(List<T> list, Object mutex) {2461return (list instanceof RandomAccess ?2462new SynchronizedRandomAccessList<>(list, mutex) :2463new SynchronizedList<>(list, mutex));2464}24652466/**2467* @serial include2468*/2469static class SynchronizedList<E>2470extends SynchronizedCollection<E>2471implements List<E> {2472@java.io.Serial2473private static final long serialVersionUID = -7754090372962971524L;24742475@SuppressWarnings("serial") // Conditionally serializable2476final List<E> list;24772478SynchronizedList(List<E> list) {2479super(list);2480this.list = list;2481}2482SynchronizedList(List<E> list, Object mutex) {2483super(list, mutex);2484this.list = list;2485}24862487public boolean equals(Object o) {2488if (this == o)2489return true;2490synchronized (mutex) {return list.equals(o);}2491}2492public int hashCode() {2493synchronized (mutex) {return list.hashCode();}2494}24952496public E get(int index) {2497synchronized (mutex) {return list.get(index);}2498}2499public E set(int index, E element) {2500synchronized (mutex) {return list.set(index, element);}2501}2502public void add(int index, E element) {2503synchronized (mutex) {list.add(index, element);}2504}2505public E remove(int index) {2506synchronized (mutex) {return list.remove(index);}2507}25082509public int indexOf(Object o) {2510synchronized (mutex) {return list.indexOf(o);}2511}2512public int lastIndexOf(Object o) {2513synchronized (mutex) {return list.lastIndexOf(o);}2514}25152516public boolean addAll(int index, Collection<? extends E> c) {2517synchronized (mutex) {return list.addAll(index, c);}2518}25192520public ListIterator<E> listIterator() {2521return list.listIterator(); // Must be manually synched by user2522}25232524public ListIterator<E> listIterator(int index) {2525return list.listIterator(index); // Must be manually synched by user2526}25272528public List<E> subList(int fromIndex, int toIndex) {2529synchronized (mutex) {2530return new SynchronizedList<>(list.subList(fromIndex, toIndex),2531mutex);2532}2533}25342535@Override2536public void replaceAll(UnaryOperator<E> operator) {2537synchronized (mutex) {list.replaceAll(operator);}2538}2539@Override2540public void sort(Comparator<? super E> c) {2541synchronized (mutex) {list.sort(c);}2542}25432544/**2545* SynchronizedRandomAccessList instances are serialized as2546* SynchronizedList instances to allow them to be deserialized2547* in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).2548* This method inverts the transformation. As a beneficial2549* side-effect, it also grafts the RandomAccess marker onto2550* SynchronizedList instances that were serialized in pre-1.4 JREs.2551*2552* Note: Unfortunately, SynchronizedRandomAccessList instances2553* serialized in 1.4.1 and deserialized in 1.4 will become2554* SynchronizedList instances, as this method was missing in 1.4.2555*/2556@java.io.Serial2557private Object readResolve() {2558return (list instanceof RandomAccess2559? new SynchronizedRandomAccessList<>(list)2560: this);2561}2562}25632564/**2565* @serial include2566*/2567static class SynchronizedRandomAccessList<E>2568extends SynchronizedList<E>2569implements RandomAccess {25702571SynchronizedRandomAccessList(List<E> list) {2572super(list);2573}25742575SynchronizedRandomAccessList(List<E> list, Object mutex) {2576super(list, mutex);2577}25782579public List<E> subList(int fromIndex, int toIndex) {2580synchronized (mutex) {2581return new SynchronizedRandomAccessList<>(2582list.subList(fromIndex, toIndex), mutex);2583}2584}25852586@java.io.Serial2587private static final long serialVersionUID = 1530674583602358482L;25882589/**2590* Allows instances to be deserialized in pre-1.4 JREs (which do2591* not have SynchronizedRandomAccessList). SynchronizedList has2592* a readResolve method that inverts this transformation upon2593* deserialization.2594*/2595@java.io.Serial2596private Object writeReplace() {2597return new SynchronizedList<>(list);2598}2599}26002601/**2602* Returns a synchronized (thread-safe) map backed by the specified2603* map. In order to guarantee serial access, it is critical that2604* <strong>all</strong> access to the backing map is accomplished2605* through the returned map.<p>2606*2607* It is imperative that the user manually synchronize on the returned2608* map when traversing any of its collection views via {@link Iterator},2609* {@link Spliterator} or {@link Stream}:2610* <pre>2611* Map m = Collections.synchronizedMap(new HashMap());2612* ...2613* Set s = m.keySet(); // Needn't be in synchronized block2614* ...2615* synchronized (m) { // Synchronizing on m, not s!2616* Iterator i = s.iterator(); // Must be in synchronized block2617* while (i.hasNext())2618* foo(i.next());2619* }2620* </pre>2621* Failure to follow this advice may result in non-deterministic behavior.2622*2623* <p>The returned map will be serializable if the specified map is2624* serializable.2625*2626* @param <K> the class of the map keys2627* @param <V> the class of the map values2628* @param m the map to be "wrapped" in a synchronized map.2629* @return a synchronized view of the specified map.2630*/2631public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {2632return new SynchronizedMap<>(m);2633}26342635/**2636* @serial include2637*/2638private static class SynchronizedMap<K,V>2639implements Map<K,V>, Serializable {2640@java.io.Serial2641private static final long serialVersionUID = 1978198479659022715L;26422643@SuppressWarnings("serial") // Conditionally serializable2644private final Map<K,V> m; // Backing Map2645@SuppressWarnings("serial") // Conditionally serializable2646final Object mutex; // Object on which to synchronize26472648SynchronizedMap(Map<K,V> m) {2649this.m = Objects.requireNonNull(m);2650mutex = this;2651}26522653SynchronizedMap(Map<K,V> m, Object mutex) {2654this.m = m;2655this.mutex = mutex;2656}26572658public int size() {2659synchronized (mutex) {return m.size();}2660}2661public boolean isEmpty() {2662synchronized (mutex) {return m.isEmpty();}2663}2664public boolean containsKey(Object key) {2665synchronized (mutex) {return m.containsKey(key);}2666}2667public boolean containsValue(Object value) {2668synchronized (mutex) {return m.containsValue(value);}2669}2670public V get(Object key) {2671synchronized (mutex) {return m.get(key);}2672}26732674public V put(K key, V value) {2675synchronized (mutex) {return m.put(key, value);}2676}2677public V remove(Object key) {2678synchronized (mutex) {return m.remove(key);}2679}2680public void putAll(Map<? extends K, ? extends V> map) {2681synchronized (mutex) {m.putAll(map);}2682}2683public void clear() {2684synchronized (mutex) {m.clear();}2685}26862687private transient Set<K> keySet;2688private transient Set<Map.Entry<K,V>> entrySet;2689private transient Collection<V> values;26902691public Set<K> keySet() {2692synchronized (mutex) {2693if (keySet==null)2694keySet = new SynchronizedSet<>(m.keySet(), mutex);2695return keySet;2696}2697}26982699public Set<Map.Entry<K,V>> entrySet() {2700synchronized (mutex) {2701if (entrySet==null)2702entrySet = new SynchronizedSet<>(m.entrySet(), mutex);2703return entrySet;2704}2705}27062707public Collection<V> values() {2708synchronized (mutex) {2709if (values==null)2710values = new SynchronizedCollection<>(m.values(), mutex);2711return values;2712}2713}27142715public boolean equals(Object o) {2716if (this == o)2717return true;2718synchronized (mutex) {return m.equals(o);}2719}2720public int hashCode() {2721synchronized (mutex) {return m.hashCode();}2722}2723public String toString() {2724synchronized (mutex) {return m.toString();}2725}27262727// Override default methods in Map2728@Override2729public V getOrDefault(Object k, V defaultValue) {2730synchronized (mutex) {return m.getOrDefault(k, defaultValue);}2731}2732@Override2733public void forEach(BiConsumer<? super K, ? super V> action) {2734synchronized (mutex) {m.forEach(action);}2735}2736@Override2737public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {2738synchronized (mutex) {m.replaceAll(function);}2739}2740@Override2741public V putIfAbsent(K key, V value) {2742synchronized (mutex) {return m.putIfAbsent(key, value);}2743}2744@Override2745public boolean remove(Object key, Object value) {2746synchronized (mutex) {return m.remove(key, value);}2747}2748@Override2749public boolean replace(K key, V oldValue, V newValue) {2750synchronized (mutex) {return m.replace(key, oldValue, newValue);}2751}2752@Override2753public V replace(K key, V value) {2754synchronized (mutex) {return m.replace(key, value);}2755}2756@Override2757public V computeIfAbsent(K key,2758Function<? super K, ? extends V> mappingFunction) {2759synchronized (mutex) {return m.computeIfAbsent(key, mappingFunction);}2760}2761@Override2762public V computeIfPresent(K key,2763BiFunction<? super K, ? super V, ? extends V> remappingFunction) {2764synchronized (mutex) {return m.computeIfPresent(key, remappingFunction);}2765}2766@Override2767public V compute(K key,2768BiFunction<? super K, ? super V, ? extends V> remappingFunction) {2769synchronized (mutex) {return m.compute(key, remappingFunction);}2770}2771@Override2772public V merge(K key, V value,2773BiFunction<? super V, ? super V, ? extends V> remappingFunction) {2774synchronized (mutex) {return m.merge(key, value, remappingFunction);}2775}27762777@java.io.Serial2778private void writeObject(ObjectOutputStream s) throws IOException {2779synchronized (mutex) {s.defaultWriteObject();}2780}2781}27822783/**2784* Returns a synchronized (thread-safe) sorted map backed by the specified2785* sorted map. In order to guarantee serial access, it is critical that2786* <strong>all</strong> access to the backing sorted map is accomplished2787* through the returned sorted map (or its views).<p>2788*2789* It is imperative that the user manually synchronize on the returned2790* sorted map when traversing any of its collection views, or the2791* collections views of any of its {@code subMap}, {@code headMap} or2792* {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or2793* {@link Stream}:2794* <pre>2795* SortedMap m = Collections.synchronizedSortedMap(new TreeMap());2796* ...2797* Set s = m.keySet(); // Needn't be in synchronized block2798* ...2799* synchronized (m) { // Synchronizing on m, not s!2800* Iterator i = s.iterator(); // Must be in synchronized block2801* while (i.hasNext())2802* foo(i.next());2803* }2804* </pre>2805* or:2806* <pre>2807* SortedMap m = Collections.synchronizedSortedMap(new TreeMap());2808* SortedMap m2 = m.subMap(foo, bar);2809* ...2810* Set s2 = m2.keySet(); // Needn't be in synchronized block2811* ...2812* synchronized (m) { // Synchronizing on m, not m2 or s2!2813* Iterator i = s2.iterator(); // Must be in synchronized block2814* while (i.hasNext())2815* foo(i.next());2816* }2817* </pre>2818* Failure to follow this advice may result in non-deterministic behavior.2819*2820* <p>The returned sorted map will be serializable if the specified2821* sorted map is serializable.2822*2823* @param <K> the class of the map keys2824* @param <V> the class of the map values2825* @param m the sorted map to be "wrapped" in a synchronized sorted map.2826* @return a synchronized view of the specified sorted map.2827*/2828public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {2829return new SynchronizedSortedMap<>(m);2830}28312832/**2833* @serial include2834*/2835static class SynchronizedSortedMap<K,V>2836extends SynchronizedMap<K,V>2837implements SortedMap<K,V>2838{2839@java.io.Serial2840private static final long serialVersionUID = -8798146769416483793L;28412842@SuppressWarnings("serial") // Conditionally serializable2843private final SortedMap<K,V> sm;28442845SynchronizedSortedMap(SortedMap<K,V> m) {2846super(m);2847sm = m;2848}2849SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {2850super(m, mutex);2851sm = m;2852}28532854public Comparator<? super K> comparator() {2855synchronized (mutex) {return sm.comparator();}2856}28572858public SortedMap<K,V> subMap(K fromKey, K toKey) {2859synchronized (mutex) {2860return new SynchronizedSortedMap<>(2861sm.subMap(fromKey, toKey), mutex);2862}2863}2864public SortedMap<K,V> headMap(K toKey) {2865synchronized (mutex) {2866return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);2867}2868}2869public SortedMap<K,V> tailMap(K fromKey) {2870synchronized (mutex) {2871return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);2872}2873}28742875public K firstKey() {2876synchronized (mutex) {return sm.firstKey();}2877}2878public K lastKey() {2879synchronized (mutex) {return sm.lastKey();}2880}2881}28822883/**2884* Returns a synchronized (thread-safe) navigable map backed by the2885* specified navigable map. In order to guarantee serial access, it is2886* critical that <strong>all</strong> access to the backing navigable map is2887* accomplished through the returned navigable map (or its views).<p>2888*2889* It is imperative that the user manually synchronize on the returned2890* navigable map when traversing any of its collection views, or the2891* collections views of any of its {@code subMap}, {@code headMap} or2892* {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or2893* {@link Stream}:2894* <pre>2895* NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());2896* ...2897* Set s = m.keySet(); // Needn't be in synchronized block2898* ...2899* synchronized (m) { // Synchronizing on m, not s!2900* Iterator i = s.iterator(); // Must be in synchronized block2901* while (i.hasNext())2902* foo(i.next());2903* }2904* </pre>2905* or:2906* <pre>2907* NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());2908* NavigableMap m2 = m.subMap(foo, true, bar, false);2909* ...2910* Set s2 = m2.keySet(); // Needn't be in synchronized block2911* ...2912* synchronized (m) { // Synchronizing on m, not m2 or s2!2913* Iterator i = s.iterator(); // Must be in synchronized block2914* while (i.hasNext())2915* foo(i.next());2916* }2917* </pre>2918* Failure to follow this advice may result in non-deterministic behavior.2919*2920* <p>The returned navigable map will be serializable if the specified2921* navigable map is serializable.2922*2923* @param <K> the class of the map keys2924* @param <V> the class of the map values2925* @param m the navigable map to be "wrapped" in a synchronized navigable2926* map2927* @return a synchronized view of the specified navigable map.2928* @since 1.82929*/2930public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) {2931return new SynchronizedNavigableMap<>(m);2932}29332934/**2935* A synchronized NavigableMap.2936*2937* @serial include2938*/2939static class SynchronizedNavigableMap<K,V>2940extends SynchronizedSortedMap<K,V>2941implements NavigableMap<K,V>2942{2943@java.io.Serial2944private static final long serialVersionUID = 699392247599746807L;29452946@SuppressWarnings("serial") // Conditionally serializable2947private final NavigableMap<K,V> nm;29482949SynchronizedNavigableMap(NavigableMap<K,V> m) {2950super(m);2951nm = m;2952}2953SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) {2954super(m, mutex);2955nm = m;2956}29572958public Entry<K, V> lowerEntry(K key)2959{ synchronized (mutex) { return nm.lowerEntry(key); } }2960public K lowerKey(K key)2961{ synchronized (mutex) { return nm.lowerKey(key); } }2962public Entry<K, V> floorEntry(K key)2963{ synchronized (mutex) { return nm.floorEntry(key); } }2964public K floorKey(K key)2965{ synchronized (mutex) { return nm.floorKey(key); } }2966public Entry<K, V> ceilingEntry(K key)2967{ synchronized (mutex) { return nm.ceilingEntry(key); } }2968public K ceilingKey(K key)2969{ synchronized (mutex) { return nm.ceilingKey(key); } }2970public Entry<K, V> higherEntry(K key)2971{ synchronized (mutex) { return nm.higherEntry(key); } }2972public K higherKey(K key)2973{ synchronized (mutex) { return nm.higherKey(key); } }2974public Entry<K, V> firstEntry()2975{ synchronized (mutex) { return nm.firstEntry(); } }2976public Entry<K, V> lastEntry()2977{ synchronized (mutex) { return nm.lastEntry(); } }2978public Entry<K, V> pollFirstEntry()2979{ synchronized (mutex) { return nm.pollFirstEntry(); } }2980public Entry<K, V> pollLastEntry()2981{ synchronized (mutex) { return nm.pollLastEntry(); } }29822983public NavigableMap<K, V> descendingMap() {2984synchronized (mutex) {2985return2986new SynchronizedNavigableMap<>(nm.descendingMap(), mutex);2987}2988}29892990public NavigableSet<K> keySet() {2991return navigableKeySet();2992}29932994public NavigableSet<K> navigableKeySet() {2995synchronized (mutex) {2996return new SynchronizedNavigableSet<>(nm.navigableKeySet(), mutex);2997}2998}29993000public NavigableSet<K> descendingKeySet() {3001synchronized (mutex) {3002return new SynchronizedNavigableSet<>(nm.descendingKeySet(), mutex);3003}3004}300530063007public SortedMap<K,V> subMap(K fromKey, K toKey) {3008synchronized (mutex) {3009return new SynchronizedNavigableMap<>(3010nm.subMap(fromKey, true, toKey, false), mutex);3011}3012}3013public SortedMap<K,V> headMap(K toKey) {3014synchronized (mutex) {3015return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex);3016}3017}3018public SortedMap<K,V> tailMap(K fromKey) {3019synchronized (mutex) {3020return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex);3021}3022}30233024public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {3025synchronized (mutex) {3026return new SynchronizedNavigableMap<>(3027nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex);3028}3029}30303031public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {3032synchronized (mutex) {3033return new SynchronizedNavigableMap<>(3034nm.headMap(toKey, inclusive), mutex);3035}3036}30373038public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {3039synchronized (mutex) {3040return new SynchronizedNavigableMap<>(3041nm.tailMap(fromKey, inclusive), mutex);3042}3043}3044}30453046// Dynamically typesafe collection wrappers30473048/**3049* Returns a dynamically typesafe view of the specified collection.3050* Any attempt to insert an element of the wrong type will result in an3051* immediate {@link ClassCastException}. Assuming a collection3052* contains no incorrectly typed elements prior to the time a3053* dynamically typesafe view is generated, and that all subsequent3054* access to the collection takes place through the view, it is3055* <i>guaranteed</i> that the collection cannot contain an incorrectly3056* typed element.3057*3058* <p>The generics mechanism in the language provides compile-time3059* (static) type checking, but it is possible to defeat this mechanism3060* with unchecked casts. Usually this is not a problem, as the compiler3061* issues warnings on all such unchecked operations. There are, however,3062* times when static type checking alone is not sufficient. For example,3063* suppose a collection is passed to a third-party library and it is3064* imperative that the library code not corrupt the collection by3065* inserting an element of the wrong type.3066*3067* <p>Another use of dynamically typesafe views is debugging. Suppose a3068* program fails with a {@code ClassCastException}, indicating that an3069* incorrectly typed element was put into a parameterized collection.3070* Unfortunately, the exception can occur at any time after the erroneous3071* element is inserted, so it typically provides little or no information3072* as to the real source of the problem. If the problem is reproducible,3073* one can quickly determine its source by temporarily modifying the3074* program to wrap the collection with a dynamically typesafe view.3075* For example, this declaration:3076* <pre> {@code3077* Collection<String> c = new HashSet<>();3078* }</pre>3079* may be replaced temporarily by this one:3080* <pre> {@code3081* Collection<String> c = Collections.checkedCollection(3082* new HashSet<>(), String.class);3083* }</pre>3084* Running the program again will cause it to fail at the point where3085* an incorrectly typed element is inserted into the collection, clearly3086* identifying the source of the problem. Once the problem is fixed, the3087* modified declaration may be reverted back to the original.3088*3089* <p>The returned collection does <i>not</i> pass the hashCode and equals3090* operations through to the backing collection, but relies on3091* {@code Object}'s {@code equals} and {@code hashCode} methods. This3092* is necessary to preserve the contracts of these operations in the case3093* that the backing collection is a set or a list.3094*3095* <p>The returned collection will be serializable if the specified3096* collection is serializable.3097*3098* <p>Since {@code null} is considered to be a value of any reference3099* type, the returned collection permits insertion of null elements3100* whenever the backing collection does.3101*3102* @param <E> the class of the objects in the collection3103* @param c the collection for which a dynamically typesafe view is to be3104* returned3105* @param type the type of element that {@code c} is permitted to hold3106* @return a dynamically typesafe view of the specified collection3107* @since 1.53108*/3109public static <E> Collection<E> checkedCollection(Collection<E> c,3110Class<E> type) {3111return new CheckedCollection<>(c, type);3112}31133114@SuppressWarnings("unchecked")3115static <T> T[] zeroLengthArray(Class<T> type) {3116return (T[]) Array.newInstance(type, 0);3117}31183119/**3120* @serial include3121*/3122static class CheckedCollection<E> implements Collection<E>, Serializable {3123@java.io.Serial3124private static final long serialVersionUID = 1578914078182001775L;31253126@SuppressWarnings("serial") // Conditionally serializable3127final Collection<E> c;3128@SuppressWarnings("serial") // Conditionally serializable3129final Class<E> type;31303131@SuppressWarnings("unchecked")3132E typeCheck(Object o) {3133if (o != null && !type.isInstance(o))3134throw new ClassCastException(badElementMsg(o));3135return (E) o;3136}31373138private String badElementMsg(Object o) {3139return "Attempt to insert " + o.getClass() +3140" element into collection with element type " + type;3141}31423143CheckedCollection(Collection<E> c, Class<E> type) {3144this.c = Objects.requireNonNull(c, "c");3145this.type = Objects.requireNonNull(type, "type");3146}31473148public int size() { return c.size(); }3149public boolean isEmpty() { return c.isEmpty(); }3150public boolean contains(Object o) { return c.contains(o); }3151public Object[] toArray() { return c.toArray(); }3152public <T> T[] toArray(T[] a) { return c.toArray(a); }3153public <T> T[] toArray(IntFunction<T[]> f) { return c.toArray(f); }3154public String toString() { return c.toString(); }3155public boolean remove(Object o) { return c.remove(o); }3156public void clear() { c.clear(); }31573158public boolean containsAll(Collection<?> coll) {3159return c.containsAll(coll);3160}3161public boolean removeAll(Collection<?> coll) {3162return c.removeAll(coll);3163}3164public boolean retainAll(Collection<?> coll) {3165return c.retainAll(coll);3166}31673168public Iterator<E> iterator() {3169// JDK-6363904 - unwrapped iterator could be typecast to3170// ListIterator with unsafe set()3171final Iterator<E> it = c.iterator();3172return new Iterator<E>() {3173public boolean hasNext() { return it.hasNext(); }3174public E next() { return it.next(); }3175public void remove() { it.remove(); }3176public void forEachRemaining(Consumer<? super E> action) {3177it.forEachRemaining(action);3178}3179};3180}31813182public boolean add(E e) { return c.add(typeCheck(e)); }31833184@SuppressWarnings("serial") // Conditionally serializable3185private E[] zeroLengthElementArray; // Lazily initialized31863187private E[] zeroLengthElementArray() {3188return zeroLengthElementArray != null ? zeroLengthElementArray :3189(zeroLengthElementArray = zeroLengthArray(type));3190}31913192@SuppressWarnings("unchecked")3193Collection<E> checkedCopyOf(Collection<? extends E> coll) {3194Object[] a;3195try {3196E[] z = zeroLengthElementArray();3197a = coll.toArray(z);3198// Defend against coll violating the toArray contract3199if (a.getClass() != z.getClass())3200a = Arrays.copyOf(a, a.length, z.getClass());3201} catch (ArrayStoreException ignore) {3202// To get better and consistent diagnostics,3203// we call typeCheck explicitly on each element.3204// We call clone() to defend against coll retaining a3205// reference to the returned array and storing a bad3206// element into it after it has been type checked.3207a = coll.toArray().clone();3208for (Object o : a)3209typeCheck(o);3210}3211// A slight abuse of the type system, but safe here.3212return (Collection<E>) Arrays.asList(a);3213}32143215public boolean addAll(Collection<? extends E> coll) {3216// Doing things this way insulates us from concurrent changes3217// in the contents of coll and provides all-or-nothing3218// semantics (which we wouldn't get if we type-checked each3219// element as we added it)3220return c.addAll(checkedCopyOf(coll));3221}32223223// Override default methods in Collection3224@Override3225public void forEach(Consumer<? super E> action) {c.forEach(action);}3226@Override3227public boolean removeIf(Predicate<? super E> filter) {3228return c.removeIf(filter);3229}3230@Override3231public Spliterator<E> spliterator() {return c.spliterator();}3232@Override3233public Stream<E> stream() {return c.stream();}3234@Override3235public Stream<E> parallelStream() {return c.parallelStream();}3236}32373238/**3239* Returns a dynamically typesafe view of the specified queue.3240* Any attempt to insert an element of the wrong type will result in3241* an immediate {@link ClassCastException}. Assuming a queue contains3242* no incorrectly typed elements prior to the time a dynamically typesafe3243* view is generated, and that all subsequent access to the queue3244* takes place through the view, it is <i>guaranteed</i> that the3245* queue cannot contain an incorrectly typed element.3246*3247* <p>A discussion of the use of dynamically typesafe views may be3248* found in the documentation for the {@link #checkedCollection3249* checkedCollection} method.3250*3251* <p>The returned queue will be serializable if the specified queue3252* is serializable.3253*3254* <p>Since {@code null} is considered to be a value of any reference3255* type, the returned queue permits insertion of {@code null} elements3256* whenever the backing queue does.3257*3258* @param <E> the class of the objects in the queue3259* @param queue the queue for which a dynamically typesafe view is to be3260* returned3261* @param type the type of element that {@code queue} is permitted to hold3262* @return a dynamically typesafe view of the specified queue3263* @since 1.83264*/3265public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type) {3266return new CheckedQueue<>(queue, type);3267}32683269/**3270* @serial include3271*/3272static class CheckedQueue<E>3273extends CheckedCollection<E>3274implements Queue<E>, Serializable3275{3276@java.io.Serial3277private static final long serialVersionUID = 1433151992604707767L;3278@SuppressWarnings("serial") // Conditionally serializable3279final Queue<E> queue;32803281CheckedQueue(Queue<E> queue, Class<E> elementType) {3282super(queue, elementType);3283this.queue = queue;3284}32853286public E element() {return queue.element();}3287public boolean equals(Object o) {return o == this || c.equals(o);}3288public int hashCode() {return c.hashCode();}3289public E peek() {return queue.peek();}3290public E poll() {return queue.poll();}3291public E remove() {return queue.remove();}3292public boolean offer(E e) {return queue.offer(typeCheck(e));}3293}32943295/**3296* Returns a dynamically typesafe view of the specified set.3297* Any attempt to insert an element of the wrong type will result in3298* an immediate {@link ClassCastException}. Assuming a set contains3299* no incorrectly typed elements prior to the time a dynamically typesafe3300* view is generated, and that all subsequent access to the set3301* takes place through the view, it is <i>guaranteed</i> that the3302* set cannot contain an incorrectly typed element.3303*3304* <p>A discussion of the use of dynamically typesafe views may be3305* found in the documentation for the {@link #checkedCollection3306* checkedCollection} method.3307*3308* <p>The returned set will be serializable if the specified set is3309* serializable.3310*3311* <p>Since {@code null} is considered to be a value of any reference3312* type, the returned set permits insertion of null elements whenever3313* the backing set does.3314*3315* @param <E> the class of the objects in the set3316* @param s the set for which a dynamically typesafe view is to be3317* returned3318* @param type the type of element that {@code s} is permitted to hold3319* @return a dynamically typesafe view of the specified set3320* @since 1.53321*/3322public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {3323return new CheckedSet<>(s, type);3324}33253326/**3327* @serial include3328*/3329static class CheckedSet<E> extends CheckedCollection<E>3330implements Set<E>, Serializable3331{3332@java.io.Serial3333private static final long serialVersionUID = 4694047833775013803L;33343335CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }33363337public boolean equals(Object o) { return o == this || c.equals(o); }3338public int hashCode() { return c.hashCode(); }3339}33403341/**3342* Returns a dynamically typesafe view of the specified sorted set.3343* Any attempt to insert an element of the wrong type will result in an3344* immediate {@link ClassCastException}. Assuming a sorted set3345* contains no incorrectly typed elements prior to the time a3346* dynamically typesafe view is generated, and that all subsequent3347* access to the sorted set takes place through the view, it is3348* <i>guaranteed</i> that the sorted set cannot contain an incorrectly3349* typed element.3350*3351* <p>A discussion of the use of dynamically typesafe views may be3352* found in the documentation for the {@link #checkedCollection3353* checkedCollection} method.3354*3355* <p>The returned sorted set will be serializable if the specified sorted3356* set is serializable.3357*3358* <p>Since {@code null} is considered to be a value of any reference3359* type, the returned sorted set permits insertion of null elements3360* whenever the backing sorted set does.3361*3362* @param <E> the class of the objects in the set3363* @param s the sorted set for which a dynamically typesafe view is to be3364* returned3365* @param type the type of element that {@code s} is permitted to hold3366* @return a dynamically typesafe view of the specified sorted set3367* @since 1.53368*/3369public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,3370Class<E> type) {3371return new CheckedSortedSet<>(s, type);3372}33733374/**3375* @serial include3376*/3377static class CheckedSortedSet<E> extends CheckedSet<E>3378implements SortedSet<E>, Serializable3379{3380@java.io.Serial3381private static final long serialVersionUID = 1599911165492914959L;33823383@SuppressWarnings("serial") // Conditionally serializable3384private final SortedSet<E> ss;33853386CheckedSortedSet(SortedSet<E> s, Class<E> type) {3387super(s, type);3388ss = s;3389}33903391public Comparator<? super E> comparator() { return ss.comparator(); }3392public E first() { return ss.first(); }3393public E last() { return ss.last(); }33943395public SortedSet<E> subSet(E fromElement, E toElement) {3396return checkedSortedSet(ss.subSet(fromElement,toElement), type);3397}3398public SortedSet<E> headSet(E toElement) {3399return checkedSortedSet(ss.headSet(toElement), type);3400}3401public SortedSet<E> tailSet(E fromElement) {3402return checkedSortedSet(ss.tailSet(fromElement), type);3403}3404}34053406/**3407* Returns a dynamically typesafe view of the specified navigable set.3408* Any attempt to insert an element of the wrong type will result in an3409* immediate {@link ClassCastException}. Assuming a navigable set3410* contains no incorrectly typed elements prior to the time a3411* dynamically typesafe view is generated, and that all subsequent3412* access to the navigable set takes place through the view, it is3413* <em>guaranteed</em> that the navigable set cannot contain an incorrectly3414* typed element.3415*3416* <p>A discussion of the use of dynamically typesafe views may be3417* found in the documentation for the {@link #checkedCollection3418* checkedCollection} method.3419*3420* <p>The returned navigable set will be serializable if the specified3421* navigable set is serializable.3422*3423* <p>Since {@code null} is considered to be a value of any reference3424* type, the returned navigable set permits insertion of null elements3425* whenever the backing sorted set does.3426*3427* @param <E> the class of the objects in the set3428* @param s the navigable set for which a dynamically typesafe view is to be3429* returned3430* @param type the type of element that {@code s} is permitted to hold3431* @return a dynamically typesafe view of the specified navigable set3432* @since 1.83433*/3434public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,3435Class<E> type) {3436return new CheckedNavigableSet<>(s, type);3437}34383439/**3440* @serial include3441*/3442static class CheckedNavigableSet<E> extends CheckedSortedSet<E>3443implements NavigableSet<E>, Serializable3444{3445@java.io.Serial3446private static final long serialVersionUID = -5429120189805438922L;34473448@SuppressWarnings("serial") // Conditionally serializable3449private final NavigableSet<E> ns;34503451CheckedNavigableSet(NavigableSet<E> s, Class<E> type) {3452super(s, type);3453ns = s;3454}34553456public E lower(E e) { return ns.lower(e); }3457public E floor(E e) { return ns.floor(e); }3458public E ceiling(E e) { return ns.ceiling(e); }3459public E higher(E e) { return ns.higher(e); }3460public E pollFirst() { return ns.pollFirst(); }3461public E pollLast() {return ns.pollLast(); }3462public NavigableSet<E> descendingSet()3463{ return checkedNavigableSet(ns.descendingSet(), type); }3464public Iterator<E> descendingIterator()3465{return checkedNavigableSet(ns.descendingSet(), type).iterator(); }34663467public NavigableSet<E> subSet(E fromElement, E toElement) {3468return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type);3469}3470public NavigableSet<E> headSet(E toElement) {3471return checkedNavigableSet(ns.headSet(toElement, false), type);3472}3473public NavigableSet<E> tailSet(E fromElement) {3474return checkedNavigableSet(ns.tailSet(fromElement, true), type);3475}34763477public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {3478return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type);3479}34803481public NavigableSet<E> headSet(E toElement, boolean inclusive) {3482return checkedNavigableSet(ns.headSet(toElement, inclusive), type);3483}34843485public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {3486return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type);3487}3488}34893490/**3491* Returns a dynamically typesafe view of the specified list.3492* Any attempt to insert an element of the wrong type will result in3493* an immediate {@link ClassCastException}. Assuming a list contains3494* no incorrectly typed elements prior to the time a dynamically typesafe3495* view is generated, and that all subsequent access to the list3496* takes place through the view, it is <i>guaranteed</i> that the3497* list cannot contain an incorrectly typed element.3498*3499* <p>A discussion of the use of dynamically typesafe views may be3500* found in the documentation for the {@link #checkedCollection3501* checkedCollection} method.3502*3503* <p>The returned list will be serializable if the specified list3504* is serializable.3505*3506* <p>Since {@code null} is considered to be a value of any reference3507* type, the returned list permits insertion of null elements whenever3508* the backing list does.3509*3510* @param <E> the class of the objects in the list3511* @param list the list for which a dynamically typesafe view is to be3512* returned3513* @param type the type of element that {@code list} is permitted to hold3514* @return a dynamically typesafe view of the specified list3515* @since 1.53516*/3517public static <E> List<E> checkedList(List<E> list, Class<E> type) {3518return (list instanceof RandomAccess ?3519new CheckedRandomAccessList<>(list, type) :3520new CheckedList<>(list, type));3521}35223523/**3524* @serial include3525*/3526static class CheckedList<E>3527extends CheckedCollection<E>3528implements List<E>3529{3530@java.io.Serial3531private static final long serialVersionUID = 65247728283967356L;3532@SuppressWarnings("serial") // Conditionally serializable3533final List<E> list;35343535CheckedList(List<E> list, Class<E> type) {3536super(list, type);3537this.list = list;3538}35393540public boolean equals(Object o) { return o == this || list.equals(o); }3541public int hashCode() { return list.hashCode(); }3542public E get(int index) { return list.get(index); }3543public E remove(int index) { return list.remove(index); }3544public int indexOf(Object o) { return list.indexOf(o); }3545public int lastIndexOf(Object o) { return list.lastIndexOf(o); }35463547public E set(int index, E element) {3548return list.set(index, typeCheck(element));3549}35503551public void add(int index, E element) {3552list.add(index, typeCheck(element));3553}35543555public boolean addAll(int index, Collection<? extends E> c) {3556return list.addAll(index, checkedCopyOf(c));3557}3558public ListIterator<E> listIterator() { return listIterator(0); }35593560public ListIterator<E> listIterator(final int index) {3561final ListIterator<E> i = list.listIterator(index);35623563return new ListIterator<E>() {3564public boolean hasNext() { return i.hasNext(); }3565public E next() { return i.next(); }3566public boolean hasPrevious() { return i.hasPrevious(); }3567public E previous() { return i.previous(); }3568public int nextIndex() { return i.nextIndex(); }3569public int previousIndex() { return i.previousIndex(); }3570public void remove() { i.remove(); }35713572public void set(E e) {3573i.set(typeCheck(e));3574}35753576public void add(E e) {3577i.add(typeCheck(e));3578}35793580@Override3581public void forEachRemaining(Consumer<? super E> action) {3582i.forEachRemaining(action);3583}3584};3585}35863587public List<E> subList(int fromIndex, int toIndex) {3588return new CheckedList<>(list.subList(fromIndex, toIndex), type);3589}35903591/**3592* {@inheritDoc}3593*3594* @throws ClassCastException if the class of an element returned by the3595* operator prevents it from being added to this collection. The3596* exception may be thrown after some elements of the list have3597* already been replaced.3598*/3599@Override3600public void replaceAll(UnaryOperator<E> operator) {3601Objects.requireNonNull(operator);3602list.replaceAll(e -> typeCheck(operator.apply(e)));3603}36043605@Override3606public void sort(Comparator<? super E> c) {3607list.sort(c);3608}3609}36103611/**3612* @serial include3613*/3614static class CheckedRandomAccessList<E> extends CheckedList<E>3615implements RandomAccess3616{3617@java.io.Serial3618private static final long serialVersionUID = 1638200125423088369L;36193620CheckedRandomAccessList(List<E> list, Class<E> type) {3621super(list, type);3622}36233624public List<E> subList(int fromIndex, int toIndex) {3625return new CheckedRandomAccessList<>(3626list.subList(fromIndex, toIndex), type);3627}3628}36293630/**3631* Returns a dynamically typesafe view of the specified map.3632* Any attempt to insert a mapping whose key or value have the wrong3633* type will result in an immediate {@link ClassCastException}.3634* Similarly, any attempt to modify the value currently associated with3635* a key will result in an immediate {@link ClassCastException},3636* whether the modification is attempted directly through the map3637* itself, or through a {@link Map.Entry} instance obtained from the3638* map's {@link Map#entrySet() entry set} view.3639*3640* <p>Assuming a map contains no incorrectly typed keys or values3641* prior to the time a dynamically typesafe view is generated, and3642* that all subsequent access to the map takes place through the view3643* (or one of its collection views), it is <i>guaranteed</i> that the3644* map cannot contain an incorrectly typed key or value.3645*3646* <p>A discussion of the use of dynamically typesafe views may be3647* found in the documentation for the {@link #checkedCollection3648* checkedCollection} method.3649*3650* <p>The returned map will be serializable if the specified map is3651* serializable.3652*3653* <p>Since {@code null} is considered to be a value of any reference3654* type, the returned map permits insertion of null keys or values3655* whenever the backing map does.3656*3657* @param <K> the class of the map keys3658* @param <V> the class of the map values3659* @param m the map for which a dynamically typesafe view is to be3660* returned3661* @param keyType the type of key that {@code m} is permitted to hold3662* @param valueType the type of value that {@code m} is permitted to hold3663* @return a dynamically typesafe view of the specified map3664* @since 1.53665*/3666public static <K, V> Map<K, V> checkedMap(Map<K, V> m,3667Class<K> keyType,3668Class<V> valueType) {3669return new CheckedMap<>(m, keyType, valueType);3670}367136723673/**3674* @serial include3675*/3676private static class CheckedMap<K,V>3677implements Map<K,V>, Serializable3678{3679@java.io.Serial3680private static final long serialVersionUID = 5742860141034234728L;36813682@SuppressWarnings("serial") // Conditionally serializable3683private final Map<K, V> m;3684@SuppressWarnings("serial") // Conditionally serializable3685final Class<K> keyType;3686@SuppressWarnings("serial") // Conditionally serializable3687final Class<V> valueType;36883689private void typeCheck(Object key, Object value) {3690if (key != null && !keyType.isInstance(key))3691throw new ClassCastException(badKeyMsg(key));36923693if (value != null && !valueType.isInstance(value))3694throw new ClassCastException(badValueMsg(value));3695}36963697private BiFunction<? super K, ? super V, ? extends V> typeCheck(3698BiFunction<? super K, ? super V, ? extends V> func) {3699Objects.requireNonNull(func);3700return (k, v) -> {3701V newValue = func.apply(k, v);3702typeCheck(k, newValue);3703return newValue;3704};3705}37063707private String badKeyMsg(Object key) {3708return "Attempt to insert " + key.getClass() +3709" key into map with key type " + keyType;3710}37113712private String badValueMsg(Object value) {3713return "Attempt to insert " + value.getClass() +3714" value into map with value type " + valueType;3715}37163717CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {3718this.m = Objects.requireNonNull(m);3719this.keyType = Objects.requireNonNull(keyType);3720this.valueType = Objects.requireNonNull(valueType);3721}37223723public int size() { return m.size(); }3724public boolean isEmpty() { return m.isEmpty(); }3725public boolean containsKey(Object key) { return m.containsKey(key); }3726public boolean containsValue(Object v) { return m.containsValue(v); }3727public V get(Object key) { return m.get(key); }3728public V remove(Object key) { return m.remove(key); }3729public void clear() { m.clear(); }3730public Set<K> keySet() { return m.keySet(); }3731public Collection<V> values() { return m.values(); }3732public boolean equals(Object o) { return o == this || m.equals(o); }3733public int hashCode() { return m.hashCode(); }3734public String toString() { return m.toString(); }37353736public V put(K key, V value) {3737typeCheck(key, value);3738return m.put(key, value);3739}37403741@SuppressWarnings("unchecked")3742public void putAll(Map<? extends K, ? extends V> t) {3743// Satisfy the following goals:3744// - good diagnostics in case of type mismatch3745// - all-or-nothing semantics3746// - protection from malicious t3747// - correct behavior if t is a concurrent map3748Object[] entries = t.entrySet().toArray();3749List<Map.Entry<K,V>> checked = new ArrayList<>(entries.length);3750for (Object o : entries) {3751Map.Entry<?,?> e = (Map.Entry<?,?>) o;3752Object k = e.getKey();3753Object v = e.getValue();3754typeCheck(k, v);3755checked.add(3756new AbstractMap.SimpleImmutableEntry<>((K)k, (V)v));3757}3758for (Map.Entry<K,V> e : checked)3759m.put(e.getKey(), e.getValue());3760}37613762private transient Set<Map.Entry<K,V>> entrySet;37633764public Set<Map.Entry<K,V>> entrySet() {3765if (entrySet==null)3766entrySet = new CheckedEntrySet<>(m.entrySet(), valueType);3767return entrySet;3768}37693770// Override default methods in Map3771@Override3772public void forEach(BiConsumer<? super K, ? super V> action) {3773m.forEach(action);3774}37753776@Override3777public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {3778m.replaceAll(typeCheck(function));3779}37803781@Override3782public V putIfAbsent(K key, V value) {3783typeCheck(key, value);3784return m.putIfAbsent(key, value);3785}37863787@Override3788public boolean remove(Object key, Object value) {3789return m.remove(key, value);3790}37913792@Override3793public boolean replace(K key, V oldValue, V newValue) {3794typeCheck(key, newValue);3795return m.replace(key, oldValue, newValue);3796}37973798@Override3799public V replace(K key, V value) {3800typeCheck(key, value);3801return m.replace(key, value);3802}38033804@Override3805public V computeIfAbsent(K key,3806Function<? super K, ? extends V> mappingFunction) {3807Objects.requireNonNull(mappingFunction);3808return m.computeIfAbsent(key, k -> {3809V value = mappingFunction.apply(k);3810typeCheck(k, value);3811return value;3812});3813}38143815@Override3816public V computeIfPresent(K key,3817BiFunction<? super K, ? super V, ? extends V> remappingFunction) {3818return m.computeIfPresent(key, typeCheck(remappingFunction));3819}38203821@Override3822public V compute(K key,3823BiFunction<? super K, ? super V, ? extends V> remappingFunction) {3824return m.compute(key, typeCheck(remappingFunction));3825}38263827@Override3828public V merge(K key, V value,3829BiFunction<? super V, ? super V, ? extends V> remappingFunction) {3830Objects.requireNonNull(remappingFunction);3831return m.merge(key, value, (v1, v2) -> {3832V newValue = remappingFunction.apply(v1, v2);3833typeCheck(null, newValue);3834return newValue;3835});3836}38373838/**3839* We need this class in addition to CheckedSet as Map.Entry permits3840* modification of the backing Map via the setValue operation. This3841* class is subtle: there are many possible attacks that must be3842* thwarted.3843*3844* @serial exclude3845*/3846static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {3847private final Set<Map.Entry<K,V>> s;3848private final Class<V> valueType;38493850CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {3851this.s = s;3852this.valueType = valueType;3853}38543855public int size() { return s.size(); }3856public boolean isEmpty() { return s.isEmpty(); }3857public String toString() { return s.toString(); }3858public int hashCode() { return s.hashCode(); }3859public void clear() { s.clear(); }38603861public boolean add(Map.Entry<K, V> e) {3862throw new UnsupportedOperationException();3863}3864public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {3865throw new UnsupportedOperationException();3866}38673868public Iterator<Map.Entry<K,V>> iterator() {3869final Iterator<Map.Entry<K, V>> i = s.iterator();38703871return new Iterator<Map.Entry<K,V>>() {3872public boolean hasNext() { return i.hasNext(); }3873public void remove() { i.remove(); }38743875public Map.Entry<K,V> next() {3876return checkedEntry(i.next(), valueType);3877}38783879public void forEachRemaining(Consumer<? super Entry<K, V>> action) {3880i.forEachRemaining(3881e -> action.accept(checkedEntry(e, valueType)));3882}3883};3884}38853886@SuppressWarnings("unchecked")3887public Object[] toArray() {3888Object[] source = s.toArray();38893890/*3891* Ensure that we don't get an ArrayStoreException even if3892* s.toArray returns an array of something other than Object3893*/3894Object[] dest = (source.getClass() == Object[].class)3895? source3896: new Object[source.length];38973898for (int i = 0; i < source.length; i++)3899dest[i] = checkedEntry((Map.Entry<K,V>)source[i],3900valueType);3901return dest;3902}39033904@SuppressWarnings("unchecked")3905public <T> T[] toArray(T[] a) {3906// We don't pass a to s.toArray, to avoid window of3907// vulnerability wherein an unscrupulous multithreaded client3908// could get his hands on raw (unwrapped) Entries from s.3909T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));39103911for (int i=0; i<arr.length; i++)3912arr[i] = (T) checkedEntry((Map.Entry<K,V>)arr[i],3913valueType);3914if (arr.length > a.length)3915return arr;39163917System.arraycopy(arr, 0, a, 0, arr.length);3918if (a.length > arr.length)3919a[arr.length] = null;3920return a;3921}39223923/**3924* This method is overridden to protect the backing set against3925* an object with a nefarious equals function that senses3926* that the equality-candidate is Map.Entry and calls its3927* setValue method.3928*/3929public boolean contains(Object o) {3930return o instanceof Map.Entry<?, ?> e3931&& s.contains((e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));3932}39333934/**3935* The bulk collection methods are overridden to protect3936* against an unscrupulous collection whose contains(Object o)3937* method senses when o is a Map.Entry, and calls o.setValue.3938*/3939public boolean containsAll(Collection<?> c) {3940for (Object o : c)3941if (!contains(o)) // Invokes safe contains() above3942return false;3943return true;3944}39453946public boolean remove(Object o) {3947if (!(o instanceof Map.Entry))3948return false;3949return s.remove(new AbstractMap.SimpleImmutableEntry3950<>((Map.Entry<?,?>)o));3951}39523953public boolean removeAll(Collection<?> c) {3954return batchRemove(c, false);3955}3956public boolean retainAll(Collection<?> c) {3957return batchRemove(c, true);3958}3959private boolean batchRemove(Collection<?> c, boolean complement) {3960Objects.requireNonNull(c);3961boolean modified = false;3962Iterator<Map.Entry<K,V>> it = iterator();3963while (it.hasNext()) {3964if (c.contains(it.next()) != complement) {3965it.remove();3966modified = true;3967}3968}3969return modified;3970}39713972public boolean equals(Object o) {3973if (o == this)3974return true;3975return o instanceof Set<?> that3976&& that.size() == s.size()3977&& containsAll(that); // Invokes safe containsAll() above3978}39793980static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,3981Class<T> valueType) {3982return new CheckedEntry<>(e, valueType);3983}39843985/**3986* This "wrapper class" serves two purposes: it prevents3987* the client from modifying the backing Map, by short-circuiting3988* the setValue method, and it protects the backing Map against3989* an ill-behaved Map.Entry that attempts to modify another3990* Map.Entry when asked to perform an equality check.3991*/3992private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {3993private final Map.Entry<K, V> e;3994private final Class<T> valueType;39953996CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {3997this.e = Objects.requireNonNull(e);3998this.valueType = Objects.requireNonNull(valueType);3999}40004001public K getKey() { return e.getKey(); }4002public V getValue() { return e.getValue(); }4003public int hashCode() { return e.hashCode(); }4004public String toString() { return e.toString(); }40054006public V setValue(V value) {4007if (value != null && !valueType.isInstance(value))4008throw new ClassCastException(badValueMsg(value));4009return e.setValue(value);4010}40114012private String badValueMsg(Object value) {4013return "Attempt to insert " + value.getClass() +4014" value into map with value type " + valueType;4015}40164017public boolean equals(Object o) {4018if (o == this)4019return true;4020if (!(o instanceof Map.Entry))4021return false;4022return e.equals(new AbstractMap.SimpleImmutableEntry4023<>((Map.Entry<?,?>)o));4024}4025}4026}4027}40284029/**4030* Returns a dynamically typesafe view of the specified sorted map.4031* Any attempt to insert a mapping whose key or value have the wrong4032* type will result in an immediate {@link ClassCastException}.4033* Similarly, any attempt to modify the value currently associated with4034* a key will result in an immediate {@link ClassCastException},4035* whether the modification is attempted directly through the map4036* itself, or through a {@link Map.Entry} instance obtained from the4037* map's {@link Map#entrySet() entry set} view.4038*4039* <p>Assuming a map contains no incorrectly typed keys or values4040* prior to the time a dynamically typesafe view is generated, and4041* that all subsequent access to the map takes place through the view4042* (or one of its collection views), it is <i>guaranteed</i> that the4043* map cannot contain an incorrectly typed key or value.4044*4045* <p>A discussion of the use of dynamically typesafe views may be4046* found in the documentation for the {@link #checkedCollection4047* checkedCollection} method.4048*4049* <p>The returned map will be serializable if the specified map is4050* serializable.4051*4052* <p>Since {@code null} is considered to be a value of any reference4053* type, the returned map permits insertion of null keys or values4054* whenever the backing map does.4055*4056* @param <K> the class of the map keys4057* @param <V> the class of the map values4058* @param m the map for which a dynamically typesafe view is to be4059* returned4060* @param keyType the type of key that {@code m} is permitted to hold4061* @param valueType the type of value that {@code m} is permitted to hold4062* @return a dynamically typesafe view of the specified map4063* @since 1.54064*/4065public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,4066Class<K> keyType,4067Class<V> valueType) {4068return new CheckedSortedMap<>(m, keyType, valueType);4069}40704071/**4072* @serial include4073*/4074static class CheckedSortedMap<K,V> extends CheckedMap<K,V>4075implements SortedMap<K,V>, Serializable4076{4077@java.io.Serial4078private static final long serialVersionUID = 1599671320688067438L;40794080@SuppressWarnings("serial") // Conditionally serializable4081private final SortedMap<K, V> sm;40824083CheckedSortedMap(SortedMap<K, V> m,4084Class<K> keyType, Class<V> valueType) {4085super(m, keyType, valueType);4086sm = m;4087}40884089public Comparator<? super K> comparator() { return sm.comparator(); }4090public K firstKey() { return sm.firstKey(); }4091public K lastKey() { return sm.lastKey(); }40924093public SortedMap<K,V> subMap(K fromKey, K toKey) {4094return checkedSortedMap(sm.subMap(fromKey, toKey),4095keyType, valueType);4096}4097public SortedMap<K,V> headMap(K toKey) {4098return checkedSortedMap(sm.headMap(toKey), keyType, valueType);4099}4100public SortedMap<K,V> tailMap(K fromKey) {4101return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);4102}4103}41044105/**4106* Returns a dynamically typesafe view of the specified navigable map.4107* Any attempt to insert a mapping whose key or value have the wrong4108* type will result in an immediate {@link ClassCastException}.4109* Similarly, any attempt to modify the value currently associated with4110* a key will result in an immediate {@link ClassCastException},4111* whether the modification is attempted directly through the map4112* itself, or through a {@link Map.Entry} instance obtained from the4113* map's {@link Map#entrySet() entry set} view.4114*4115* <p>Assuming a map contains no incorrectly typed keys or values4116* prior to the time a dynamically typesafe view is generated, and4117* that all subsequent access to the map takes place through the view4118* (or one of its collection views), it is <em>guaranteed</em> that the4119* map cannot contain an incorrectly typed key or value.4120*4121* <p>A discussion of the use of dynamically typesafe views may be4122* found in the documentation for the {@link #checkedCollection4123* checkedCollection} method.4124*4125* <p>The returned map will be serializable if the specified map is4126* serializable.4127*4128* <p>Since {@code null} is considered to be a value of any reference4129* type, the returned map permits insertion of null keys or values4130* whenever the backing map does.4131*4132* @param <K> type of map keys4133* @param <V> type of map values4134* @param m the map for which a dynamically typesafe view is to be4135* returned4136* @param keyType the type of key that {@code m} is permitted to hold4137* @param valueType the type of value that {@code m} is permitted to hold4138* @return a dynamically typesafe view of the specified map4139* @since 1.84140*/4141public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m,4142Class<K> keyType,4143Class<V> valueType) {4144return new CheckedNavigableMap<>(m, keyType, valueType);4145}41464147/**4148* @serial include4149*/4150static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V>4151implements NavigableMap<K,V>, Serializable4152{4153@java.io.Serial4154private static final long serialVersionUID = -4852462692372534096L;41554156@SuppressWarnings("serial") // Conditionally serializable4157private final NavigableMap<K, V> nm;41584159CheckedNavigableMap(NavigableMap<K, V> m,4160Class<K> keyType, Class<V> valueType) {4161super(m, keyType, valueType);4162nm = m;4163}41644165public Comparator<? super K> comparator() { return nm.comparator(); }4166public K firstKey() { return nm.firstKey(); }4167public K lastKey() { return nm.lastKey(); }41684169public Entry<K, V> lowerEntry(K key) {4170Entry<K,V> lower = nm.lowerEntry(key);4171return (null != lower)4172? new CheckedMap.CheckedEntrySet.CheckedEntry<>(lower, valueType)4173: null;4174}41754176public K lowerKey(K key) { return nm.lowerKey(key); }41774178public Entry<K, V> floorEntry(K key) {4179Entry<K,V> floor = nm.floorEntry(key);4180return (null != floor)4181? new CheckedMap.CheckedEntrySet.CheckedEntry<>(floor, valueType)4182: null;4183}41844185public K floorKey(K key) { return nm.floorKey(key); }41864187public Entry<K, V> ceilingEntry(K key) {4188Entry<K,V> ceiling = nm.ceilingEntry(key);4189return (null != ceiling)4190? new CheckedMap.CheckedEntrySet.CheckedEntry<>(ceiling, valueType)4191: null;4192}41934194public K ceilingKey(K key) { return nm.ceilingKey(key); }41954196public Entry<K, V> higherEntry(K key) {4197Entry<K,V> higher = nm.higherEntry(key);4198return (null != higher)4199? new CheckedMap.CheckedEntrySet.CheckedEntry<>(higher, valueType)4200: null;4201}42024203public K higherKey(K key) { return nm.higherKey(key); }42044205public Entry<K, V> firstEntry() {4206Entry<K,V> first = nm.firstEntry();4207return (null != first)4208? new CheckedMap.CheckedEntrySet.CheckedEntry<>(first, valueType)4209: null;4210}42114212public Entry<K, V> lastEntry() {4213Entry<K,V> last = nm.lastEntry();4214return (null != last)4215? new CheckedMap.CheckedEntrySet.CheckedEntry<>(last, valueType)4216: null;4217}42184219public Entry<K, V> pollFirstEntry() {4220Entry<K,V> entry = nm.pollFirstEntry();4221return (null == entry)4222? null4223: new CheckedMap.CheckedEntrySet.CheckedEntry<>(entry, valueType);4224}42254226public Entry<K, V> pollLastEntry() {4227Entry<K,V> entry = nm.pollLastEntry();4228return (null == entry)4229? null4230: new CheckedMap.CheckedEntrySet.CheckedEntry<>(entry, valueType);4231}42324233public NavigableMap<K, V> descendingMap() {4234return checkedNavigableMap(nm.descendingMap(), keyType, valueType);4235}42364237public NavigableSet<K> keySet() {4238return navigableKeySet();4239}42404241public NavigableSet<K> navigableKeySet() {4242return checkedNavigableSet(nm.navigableKeySet(), keyType);4243}42444245public NavigableSet<K> descendingKeySet() {4246return checkedNavigableSet(nm.descendingKeySet(), keyType);4247}42484249@Override4250public NavigableMap<K,V> subMap(K fromKey, K toKey) {4251return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false),4252keyType, valueType);4253}42544255@Override4256public NavigableMap<K,V> headMap(K toKey) {4257return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType);4258}42594260@Override4261public NavigableMap<K,V> tailMap(K fromKey) {4262return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType);4263}42644265public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {4266return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType);4267}42684269public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {4270return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType);4271}42724273public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {4274return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType);4275}4276}42774278// Empty collections42794280/**4281* Returns an iterator that has no elements. More precisely,4282*4283* <ul>4284* <li>{@link Iterator#hasNext hasNext} always returns {@code4285* false}.</li>4286* <li>{@link Iterator#next next} always throws {@link4287* NoSuchElementException}.</li>4288* <li>{@link Iterator#remove remove} always throws {@link4289* IllegalStateException}.</li>4290* </ul>4291*4292* <p>Implementations of this method are permitted, but not4293* required, to return the same object from multiple invocations.4294*4295* @param <T> type of elements, if there were any, in the iterator4296* @return an empty iterator4297* @since 1.74298*/4299@SuppressWarnings("unchecked")4300public static <T> Iterator<T> emptyIterator() {4301return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;4302}43034304private static class EmptyIterator<E> implements Iterator<E> {4305static final EmptyIterator<Object> EMPTY_ITERATOR4306= new EmptyIterator<>();43074308public boolean hasNext() { return false; }4309public E next() { throw new NoSuchElementException(); }4310public void remove() { throw new IllegalStateException(); }4311@Override4312public void forEachRemaining(Consumer<? super E> action) {4313Objects.requireNonNull(action);4314}4315}43164317/**4318* Returns a list iterator that has no elements. More precisely,4319*4320* <ul>4321* <li>{@link Iterator#hasNext hasNext} and {@link4322* ListIterator#hasPrevious hasPrevious} always return {@code4323* false}.</li>4324* <li>{@link Iterator#next next} and {@link ListIterator#previous4325* previous} always throw {@link NoSuchElementException}.</li>4326* <li>{@link Iterator#remove remove} and {@link ListIterator#set4327* set} always throw {@link IllegalStateException}.</li>4328* <li>{@link ListIterator#add add} always throws {@link4329* UnsupportedOperationException}.</li>4330* <li>{@link ListIterator#nextIndex nextIndex} always returns4331* {@code 0}.</li>4332* <li>{@link ListIterator#previousIndex previousIndex} always4333* returns {@code -1}.</li>4334* </ul>4335*4336* <p>Implementations of this method are permitted, but not4337* required, to return the same object from multiple invocations.4338*4339* @param <T> type of elements, if there were any, in the iterator4340* @return an empty list iterator4341* @since 1.74342*/4343@SuppressWarnings("unchecked")4344public static <T> ListIterator<T> emptyListIterator() {4345return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR;4346}43474348private static class EmptyListIterator<E>4349extends EmptyIterator<E>4350implements ListIterator<E>4351{4352static final EmptyListIterator<Object> EMPTY_ITERATOR4353= new EmptyListIterator<>();43544355public boolean hasPrevious() { return false; }4356public E previous() { throw new NoSuchElementException(); }4357public int nextIndex() { return 0; }4358public int previousIndex() { return -1; }4359public void set(E e) { throw new IllegalStateException(); }4360public void add(E e) { throw new UnsupportedOperationException(); }4361}43624363/**4364* Returns an enumeration that has no elements. More precisely,4365*4366* <ul>4367* <li>{@link Enumeration#hasMoreElements hasMoreElements} always4368* returns {@code false}.</li>4369* <li> {@link Enumeration#nextElement nextElement} always throws4370* {@link NoSuchElementException}.</li>4371* </ul>4372*4373* <p>Implementations of this method are permitted, but not4374* required, to return the same object from multiple invocations.4375*4376* @param <T> the class of the objects in the enumeration4377* @return an empty enumeration4378* @since 1.74379*/4380@SuppressWarnings("unchecked")4381public static <T> Enumeration<T> emptyEnumeration() {4382return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;4383}43844385private static class EmptyEnumeration<E> implements Enumeration<E> {4386static final EmptyEnumeration<Object> EMPTY_ENUMERATION4387= new EmptyEnumeration<>();43884389public boolean hasMoreElements() { return false; }4390public E nextElement() { throw new NoSuchElementException(); }4391public Iterator<E> asIterator() { return emptyIterator(); }4392}43934394/**4395* The empty set (immutable). This set is serializable.4396*4397* @see #emptySet()4398*/4399@SuppressWarnings("rawtypes")4400public static final Set EMPTY_SET = new EmptySet<>();44014402/**4403* Returns an empty set (immutable). This set is serializable.4404* Unlike the like-named field, this method is parameterized.4405*4406* <p>This example illustrates the type-safe way to obtain an empty set:4407* <pre>4408* Set<String> s = Collections.emptySet();4409* </pre>4410* @implNote Implementations of this method need not create a separate4411* {@code Set} object for each call. Using this method is likely to have4412* comparable cost to using the like-named field. (Unlike this method, the4413* field does not provide type safety.)4414*4415* @param <T> the class of the objects in the set4416* @return the empty set4417*4418* @see #EMPTY_SET4419* @since 1.54420*/4421@SuppressWarnings("unchecked")4422public static final <T> Set<T> emptySet() {4423return (Set<T>) EMPTY_SET;4424}44254426/**4427* @serial include4428*/4429private static class EmptySet<E>4430extends AbstractSet<E>4431implements Serializable4432{4433@java.io.Serial4434private static final long serialVersionUID = 1582296315990362920L;44354436public Iterator<E> iterator() { return emptyIterator(); }44374438public int size() {return 0;}4439public boolean isEmpty() {return true;}4440public void clear() {}44414442public boolean contains(Object obj) {return false;}4443public boolean containsAll(Collection<?> c) { return c.isEmpty(); }44444445public Object[] toArray() { return new Object[0]; }44464447public <T> T[] toArray(T[] a) {4448if (a.length > 0)4449a[0] = null;4450return a;4451}44524453// Override default methods in Collection4454@Override4455public void forEach(Consumer<? super E> action) {4456Objects.requireNonNull(action);4457}4458@Override4459public boolean removeIf(Predicate<? super E> filter) {4460Objects.requireNonNull(filter);4461return false;4462}4463@Override4464public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }44654466// Preserves singleton property4467@java.io.Serial4468private Object readResolve() {4469return EMPTY_SET;4470}44714472@Override4473public int hashCode() {4474return 0;4475}4476}44774478/**4479* Returns an empty sorted set (immutable). This set is serializable.4480*4481* <p>This example illustrates the type-safe way to obtain an empty4482* sorted set:4483* <pre> {@code4484* SortedSet<String> s = Collections.emptySortedSet();4485* }</pre>4486*4487* @implNote Implementations of this method need not create a separate4488* {@code SortedSet} object for each call.4489*4490* @param <E> type of elements, if there were any, in the set4491* @return the empty sorted set4492* @since 1.84493*/4494@SuppressWarnings("unchecked")4495public static <E> SortedSet<E> emptySortedSet() {4496return (SortedSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;4497}44984499/**4500* Returns an empty navigable set (immutable). This set is serializable.4501*4502* <p>This example illustrates the type-safe way to obtain an empty4503* navigable set:4504* <pre> {@code4505* NavigableSet<String> s = Collections.emptyNavigableSet();4506* }</pre>4507*4508* @implNote Implementations of this method need not4509* create a separate {@code NavigableSet} object for each call.4510*4511* @param <E> type of elements, if there were any, in the set4512* @return the empty navigable set4513* @since 1.84514*/4515@SuppressWarnings("unchecked")4516public static <E> NavigableSet<E> emptyNavigableSet() {4517return (NavigableSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;4518}45194520/**4521* The empty list (immutable). This list is serializable.4522*4523* @see #emptyList()4524*/4525@SuppressWarnings("rawtypes")4526public static final List EMPTY_LIST = new EmptyList<>();45274528/**4529* Returns an empty list (immutable). This list is serializable.4530*4531* <p>This example illustrates the type-safe way to obtain an empty list:4532* <pre>4533* List<String> s = Collections.emptyList();4534* </pre>4535*4536* @implNote4537* Implementations of this method need not create a separate {@code List}4538* object for each call. Using this method is likely to have comparable4539* cost to using the like-named field. (Unlike this method, the field does4540* not provide type safety.)4541*4542* @param <T> type of elements, if there were any, in the list4543* @return an empty immutable list4544*4545* @see #EMPTY_LIST4546* @since 1.54547*/4548@SuppressWarnings("unchecked")4549public static final <T> List<T> emptyList() {4550return (List<T>) EMPTY_LIST;4551}45524553/**4554* @serial include4555*/4556private static class EmptyList<E>4557extends AbstractList<E>4558implements RandomAccess, Serializable {4559@java.io.Serial4560private static final long serialVersionUID = 8842843931221139166L;45614562public Iterator<E> iterator() {4563return emptyIterator();4564}4565public ListIterator<E> listIterator() {4566return emptyListIterator();4567}45684569public int size() {return 0;}4570public boolean isEmpty() {return true;}4571public void clear() {}45724573public boolean contains(Object obj) {return false;}4574public boolean containsAll(Collection<?> c) { return c.isEmpty(); }45754576public Object[] toArray() { return new Object[0]; }45774578public <T> T[] toArray(T[] a) {4579if (a.length > 0)4580a[0] = null;4581return a;4582}45834584public E get(int index) {4585throw new IndexOutOfBoundsException("Index: "+index);4586}45874588public boolean equals(Object o) {4589return (o instanceof List) && ((List<?>)o).isEmpty();4590}45914592public int hashCode() { return 1; }45934594@Override4595public boolean removeIf(Predicate<? super E> filter) {4596Objects.requireNonNull(filter);4597return false;4598}4599@Override4600public void replaceAll(UnaryOperator<E> operator) {4601Objects.requireNonNull(operator);4602}4603@Override4604public void sort(Comparator<? super E> c) {4605}46064607// Override default methods in Collection4608@Override4609public void forEach(Consumer<? super E> action) {4610Objects.requireNonNull(action);4611}46124613@Override4614public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }46154616// Preserves singleton property4617@java.io.Serial4618private Object readResolve() {4619return EMPTY_LIST;4620}4621}46224623/**4624* The empty map (immutable). This map is serializable.4625*4626* @see #emptyMap()4627* @since 1.34628*/4629@SuppressWarnings("rawtypes")4630public static final Map EMPTY_MAP = new EmptyMap<>();46314632/**4633* Returns an empty map (immutable). This map is serializable.4634*4635* <p>This example illustrates the type-safe way to obtain an empty map:4636* <pre>4637* Map<String, Date> s = Collections.emptyMap();4638* </pre>4639* @implNote Implementations of this method need not create a separate4640* {@code Map} object for each call. Using this method is likely to have4641* comparable cost to using the like-named field. (Unlike this method, the4642* field does not provide type safety.)4643*4644* @param <K> the class of the map keys4645* @param <V> the class of the map values4646* @return an empty map4647* @see #EMPTY_MAP4648* @since 1.54649*/4650@SuppressWarnings("unchecked")4651public static final <K,V> Map<K,V> emptyMap() {4652return (Map<K,V>) EMPTY_MAP;4653}46544655/**4656* Returns an empty sorted map (immutable). This map is serializable.4657*4658* <p>This example illustrates the type-safe way to obtain an empty map:4659* <pre> {@code4660* SortedMap<String, Date> s = Collections.emptySortedMap();4661* }</pre>4662*4663* @implNote Implementations of this method need not create a separate4664* {@code SortedMap} object for each call.4665*4666* @param <K> the class of the map keys4667* @param <V> the class of the map values4668* @return an empty sorted map4669* @since 1.84670*/4671@SuppressWarnings("unchecked")4672public static final <K,V> SortedMap<K,V> emptySortedMap() {4673return (SortedMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;4674}46754676/**4677* Returns an empty navigable map (immutable). This map is serializable.4678*4679* <p>This example illustrates the type-safe way to obtain an empty map:4680* <pre> {@code4681* NavigableMap<String, Date> s = Collections.emptyNavigableMap();4682* }</pre>4683*4684* @implNote Implementations of this method need not create a separate4685* {@code NavigableMap} object for each call.4686*4687* @param <K> the class of the map keys4688* @param <V> the class of the map values4689* @return an empty navigable map4690* @since 1.84691*/4692@SuppressWarnings("unchecked")4693public static final <K,V> NavigableMap<K,V> emptyNavigableMap() {4694return (NavigableMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;4695}46964697/**4698* @serial include4699*/4700private static class EmptyMap<K,V>4701extends AbstractMap<K,V>4702implements Serializable4703{4704@java.io.Serial4705private static final long serialVersionUID = 6428348081105594320L;47064707public int size() {return 0;}4708public boolean isEmpty() {return true;}4709public void clear() {}4710public boolean containsKey(Object key) {return false;}4711public boolean containsValue(Object value) {return false;}4712public V get(Object key) {return null;}4713public Set<K> keySet() {return emptySet();}4714public Collection<V> values() {return emptySet();}4715public Set<Map.Entry<K,V>> entrySet() {return emptySet();}47164717public boolean equals(Object o) {4718return (o instanceof Map) && ((Map<?,?>)o).isEmpty();4719}47204721public int hashCode() {return 0;}47224723// Override default methods in Map4724@Override4725@SuppressWarnings("unchecked")4726public V getOrDefault(Object k, V defaultValue) {4727return defaultValue;4728}47294730@Override4731public void forEach(BiConsumer<? super K, ? super V> action) {4732Objects.requireNonNull(action);4733}47344735@Override4736public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {4737Objects.requireNonNull(function);4738}47394740@Override4741public V putIfAbsent(K key, V value) {4742throw new UnsupportedOperationException();4743}47444745@Override4746public boolean remove(Object key, Object value) {4747throw new UnsupportedOperationException();4748}47494750@Override4751public boolean replace(K key, V oldValue, V newValue) {4752throw new UnsupportedOperationException();4753}47544755@Override4756public V replace(K key, V value) {4757throw new UnsupportedOperationException();4758}47594760@Override4761public V computeIfAbsent(K key,4762Function<? super K, ? extends V> mappingFunction) {4763throw new UnsupportedOperationException();4764}47654766@Override4767public V computeIfPresent(K key,4768BiFunction<? super K, ? super V, ? extends V> remappingFunction) {4769throw new UnsupportedOperationException();4770}47714772@Override4773public V compute(K key,4774BiFunction<? super K, ? super V, ? extends V> remappingFunction) {4775throw new UnsupportedOperationException();4776}47774778@Override4779public V merge(K key, V value,4780BiFunction<? super V, ? super V, ? extends V> remappingFunction) {4781throw new UnsupportedOperationException();4782}47834784// Preserves singleton property4785@java.io.Serial4786private Object readResolve() {4787return EMPTY_MAP;4788}4789}47904791// Singleton collections47924793/**4794* Returns an immutable set containing only the specified object.4795* The returned set is serializable.4796*4797* @param <T> the class of the objects in the set4798* @param o the sole object to be stored in the returned set.4799* @return an immutable set containing only the specified object.4800*/4801public static <T> Set<T> singleton(T o) {4802return new SingletonSet<>(o);4803}48044805static <E> Iterator<E> singletonIterator(final E e) {4806return new Iterator<E>() {4807private boolean hasNext = true;4808public boolean hasNext() {4809return hasNext;4810}4811public E next() {4812if (hasNext) {4813hasNext = false;4814return e;4815}4816throw new NoSuchElementException();4817}4818public void remove() {4819throw new UnsupportedOperationException();4820}4821@Override4822public void forEachRemaining(Consumer<? super E> action) {4823Objects.requireNonNull(action);4824if (hasNext) {4825hasNext = false;4826action.accept(e);4827}4828}4829};4830}48314832/**4833* Creates a {@code Spliterator} with only the specified element4834*4835* @param <T> Type of elements4836* @return A singleton {@code Spliterator}4837*/4838static <T> Spliterator<T> singletonSpliterator(final T element) {4839return new Spliterator<T>() {4840long est = 1;48414842@Override4843public Spliterator<T> trySplit() {4844return null;4845}48464847@Override4848public boolean tryAdvance(Consumer<? super T> consumer) {4849Objects.requireNonNull(consumer);4850if (est > 0) {4851est--;4852consumer.accept(element);4853return true;4854}4855return false;4856}48574858@Override4859public void forEachRemaining(Consumer<? super T> consumer) {4860tryAdvance(consumer);4861}48624863@Override4864public long estimateSize() {4865return est;4866}48674868@Override4869public int characteristics() {4870int value = (element != null) ? Spliterator.NONNULL : 0;48714872return value | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE |4873Spliterator.DISTINCT | Spliterator.ORDERED;4874}4875};4876}48774878/**4879* @serial include4880*/4881private static class SingletonSet<E>4882extends AbstractSet<E>4883implements Serializable4884{4885@java.io.Serial4886private static final long serialVersionUID = 3193687207550431679L;48874888@SuppressWarnings("serial") // Conditionally serializable4889private final E element;48904891SingletonSet(E e) {element = e;}48924893public Iterator<E> iterator() {4894return singletonIterator(element);4895}48964897public int size() {return 1;}48984899public boolean contains(Object o) {return eq(o, element);}49004901// Override default methods for Collection4902@Override4903public void forEach(Consumer<? super E> action) {4904action.accept(element);4905}4906@Override4907public Spliterator<E> spliterator() {4908return singletonSpliterator(element);4909}4910@Override4911public boolean removeIf(Predicate<? super E> filter) {4912throw new UnsupportedOperationException();4913}4914@Override4915public int hashCode() {4916return Objects.hashCode(element);4917}4918}49194920/**4921* Returns an immutable list containing only the specified object.4922* The returned list is serializable.4923*4924* @param <T> the class of the objects in the list4925* @param o the sole object to be stored in the returned list.4926* @return an immutable list containing only the specified object.4927* @since 1.34928*/4929public static <T> List<T> singletonList(T o) {4930return new SingletonList<>(o);4931}49324933/**4934* @serial include4935*/4936private static class SingletonList<E>4937extends AbstractList<E>4938implements RandomAccess, Serializable {49394940@java.io.Serial4941private static final long serialVersionUID = 3093736618740652951L;49424943@SuppressWarnings("serial") // Conditionally serializable4944private final E element;49454946SingletonList(E obj) {element = obj;}49474948public Iterator<E> iterator() {4949return singletonIterator(element);4950}49514952public int size() {return 1;}49534954public boolean contains(Object obj) {return eq(obj, element);}49554956public E get(int index) {4957if (index != 0)4958throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");4959return element;4960}49614962// Override default methods for Collection4963@Override4964public void forEach(Consumer<? super E> action) {4965action.accept(element);4966}4967@Override4968public boolean removeIf(Predicate<? super E> filter) {4969throw new UnsupportedOperationException();4970}4971@Override4972public void replaceAll(UnaryOperator<E> operator) {4973throw new UnsupportedOperationException();4974}4975@Override4976public void sort(Comparator<? super E> c) {4977}4978@Override4979public Spliterator<E> spliterator() {4980return singletonSpliterator(element);4981}4982@Override4983public int hashCode() {4984return 31 + Objects.hashCode(element);4985}4986}49874988/**4989* Returns an immutable map, mapping only the specified key to the4990* specified value. The returned map is serializable.4991*4992* @param <K> the class of the map keys4993* @param <V> the class of the map values4994* @param key the sole key to be stored in the returned map.4995* @param value the value to which the returned map maps {@code key}.4996* @return an immutable map containing only the specified key-value4997* mapping.4998* @since 1.34999*/5000public static <K,V> Map<K,V> singletonMap(K key, V value) {5001return new SingletonMap<>(key, value);5002}50035004/**5005* @serial include5006*/5007private static class SingletonMap<K,V>5008extends AbstractMap<K,V>5009implements Serializable {5010@java.io.Serial5011private static final long serialVersionUID = -6979724477215052911L;50125013@SuppressWarnings("serial") // Conditionally serializable5014private final K k;5015@SuppressWarnings("serial") // Conditionally serializable5016private final V v;50175018SingletonMap(K key, V value) {5019k = key;5020v = value;5021}50225023public int size() {return 1;}5024public boolean isEmpty() {return false;}5025public boolean containsKey(Object key) {return eq(key, k);}5026public boolean containsValue(Object value) {return eq(value, v);}5027public V get(Object key) {return (eq(key, k) ? v : null);}50285029private transient Set<K> keySet;5030private transient Set<Map.Entry<K,V>> entrySet;5031private transient Collection<V> values;50325033public Set<K> keySet() {5034if (keySet==null)5035keySet = singleton(k);5036return keySet;5037}50385039public Set<Map.Entry<K,V>> entrySet() {5040if (entrySet==null)5041entrySet = Collections.<Map.Entry<K,V>>singleton(5042new SimpleImmutableEntry<>(k, v));5043return entrySet;5044}50455046public Collection<V> values() {5047if (values==null)5048values = singleton(v);5049return values;5050}50515052// Override default methods in Map5053@Override5054public V getOrDefault(Object key, V defaultValue) {5055return eq(key, k) ? v : defaultValue;5056}50575058@Override5059public void forEach(BiConsumer<? super K, ? super V> action) {5060action.accept(k, v);5061}50625063@Override5064public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {5065throw new UnsupportedOperationException();5066}50675068@Override5069public V putIfAbsent(K key, V value) {5070throw new UnsupportedOperationException();5071}50725073@Override5074public boolean remove(Object key, Object value) {5075throw new UnsupportedOperationException();5076}50775078@Override5079public boolean replace(K key, V oldValue, V newValue) {5080throw new UnsupportedOperationException();5081}50825083@Override5084public V replace(K key, V value) {5085throw new UnsupportedOperationException();5086}50875088@Override5089public V computeIfAbsent(K key,5090Function<? super K, ? extends V> mappingFunction) {5091throw new UnsupportedOperationException();5092}50935094@Override5095public V computeIfPresent(K key,5096BiFunction<? super K, ? super V, ? extends V> remappingFunction) {5097throw new UnsupportedOperationException();5098}50995100@Override5101public V compute(K key,5102BiFunction<? super K, ? super V, ? extends V> remappingFunction) {5103throw new UnsupportedOperationException();5104}51055106@Override5107public V merge(K key, V value,5108BiFunction<? super V, ? super V, ? extends V> remappingFunction) {5109throw new UnsupportedOperationException();5110}51115112@Override5113public int hashCode() {5114return Objects.hashCode(k) ^ Objects.hashCode(v);5115}5116}51175118// Miscellaneous51195120/**5121* Returns an immutable list consisting of {@code n} copies of the5122* specified object. The newly allocated data object is tiny (it contains5123* a single reference to the data object). This method is useful in5124* combination with the {@code List.addAll} method to grow lists.5125* The returned list is serializable.5126*5127* @param <T> the class of the object to copy and of the objects5128* in the returned list.5129* @param n the number of elements in the returned list.5130* @param o the element to appear repeatedly in the returned list.5131* @return an immutable list consisting of {@code n} copies of the5132* specified object.5133* @throws IllegalArgumentException if {@code n < 0}5134* @see List#addAll(Collection)5135* @see List#addAll(int, Collection)5136*/5137public static <T> List<T> nCopies(int n, T o) {5138if (n < 0)5139throw new IllegalArgumentException("List length = " + n);5140return new CopiesList<>(n, o);5141}51425143/**5144* @serial include5145*/5146private static class CopiesList<E>5147extends AbstractList<E>5148implements RandomAccess, Serializable5149{5150@java.io.Serial5151private static final long serialVersionUID = 2739099268398711800L;51525153final int n;5154@SuppressWarnings("serial") // Conditionally serializable5155final E element;51565157CopiesList(int n, E e) {5158assert n >= 0;5159this.n = n;5160element = e;5161}51625163public int size() {5164return n;5165}51665167public boolean contains(Object obj) {5168return n != 0 && eq(obj, element);5169}51705171public int indexOf(Object o) {5172return contains(o) ? 0 : -1;5173}51745175public int lastIndexOf(Object o) {5176return contains(o) ? n - 1 : -1;5177}51785179public E get(int index) {5180if (index < 0 || index >= n)5181throw new IndexOutOfBoundsException("Index: "+index+5182", Size: "+n);5183return element;5184}51855186public Object[] toArray() {5187final Object[] a = new Object[n];5188if (element != null)5189Arrays.fill(a, 0, n, element);5190return a;5191}51925193@SuppressWarnings("unchecked")5194public <T> T[] toArray(T[] a) {5195final int n = this.n;5196if (a.length < n) {5197a = (T[])java.lang.reflect.Array5198.newInstance(a.getClass().getComponentType(), n);5199if (element != null)5200Arrays.fill(a, 0, n, element);5201} else {5202Arrays.fill(a, 0, n, element);5203if (a.length > n)5204a[n] = null;5205}5206return a;5207}52085209public List<E> subList(int fromIndex, int toIndex) {5210if (fromIndex < 0)5211throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);5212if (toIndex > n)5213throw new IndexOutOfBoundsException("toIndex = " + toIndex);5214if (fromIndex > toIndex)5215throw new IllegalArgumentException("fromIndex(" + fromIndex +5216") > toIndex(" + toIndex + ")");5217return new CopiesList<>(toIndex - fromIndex, element);5218}52195220@Override5221public int hashCode() {5222if (n == 0) return 1;5223// hashCode of n repeating elements is 31^n + elementHash * Sum(31^k, k = 0..n-1)5224// this implementation completes in O(log(n)) steps taking advantage of5225// 31^(2*n) = (31^n)^2 and Sum(31^k, k = 0..(2*n-1)) = Sum(31^k, k = 0..n-1) * (31^n + 1)5226int pow = 31;5227int sum = 1;5228for (int i = Integer.numberOfLeadingZeros(n) + 1; i < Integer.SIZE; i++) {5229sum *= pow + 1;5230pow *= pow;5231if ((n << i) < 0) {5232pow *= 31;5233sum = sum * 31 + 1;5234}5235}5236return pow + sum * (element == null ? 0 : element.hashCode());5237}52385239@Override5240public boolean equals(Object o) {5241if (o == this)5242return true;5243if (o instanceof CopiesList<?> other) {5244return n == other.n && (n == 0 || eq(element, other.element));5245}5246if (!(o instanceof List))5247return false;52485249int remaining = n;5250E e = element;5251Iterator<?> itr = ((List<?>) o).iterator();5252if (e == null) {5253while (itr.hasNext() && remaining-- > 0) {5254if (itr.next() != null)5255return false;5256}5257} else {5258while (itr.hasNext() && remaining-- > 0) {5259if (!e.equals(itr.next()))5260return false;5261}5262}5263return remaining == 0 && !itr.hasNext();5264}52655266// Override default methods in Collection5267@Override5268public Stream<E> stream() {5269return IntStream.range(0, n).mapToObj(i -> element);5270}52715272@Override5273public Stream<E> parallelStream() {5274return IntStream.range(0, n).parallel().mapToObj(i -> element);5275}52765277@Override5278public Spliterator<E> spliterator() {5279return stream().spliterator();5280}52815282@java.io.Serial5283private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {5284ois.defaultReadObject();5285SharedSecrets.getJavaObjectInputStreamAccess().checkArray(ois, Object[].class, n);5286}5287}52885289/**5290* Returns a comparator that imposes the reverse of the <em>natural5291* ordering</em> on a collection of objects that implement the5292* {@code Comparable} interface. (The natural ordering is the ordering5293* imposed by the objects' own {@code compareTo} method.) This enables a5294* simple idiom for sorting (or maintaining) collections (or arrays) of5295* objects that implement the {@code Comparable} interface in5296* reverse-natural-order. For example, suppose {@code a} is an array of5297* strings. Then: <pre>5298* Arrays.sort(a, Collections.reverseOrder());5299* </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>5300*5301* The returned comparator is serializable.5302*5303* @param <T> the class of the objects compared by the comparator5304* @return A comparator that imposes the reverse of the <i>natural5305* ordering</i> on a collection of objects that implement5306* the {@code Comparable} interface.5307* @see Comparable5308*/5309@SuppressWarnings("unchecked")5310public static <T> Comparator<T> reverseOrder() {5311return (Comparator<T>) ReverseComparator.REVERSE_ORDER;5312}53135314/**5315* @serial include5316*/5317private static class ReverseComparator5318implements Comparator<Comparable<Object>>, Serializable {53195320@java.io.Serial5321private static final long serialVersionUID = 7207038068494060240L;53225323static final ReverseComparator REVERSE_ORDER5324= new ReverseComparator();53255326public int compare(Comparable<Object> c1, Comparable<Object> c2) {5327return c2.compareTo(c1);5328}53295330@java.io.Serial5331private Object readResolve() { return Collections.reverseOrder(); }53325333@Override5334public Comparator<Comparable<Object>> reversed() {5335return Comparator.naturalOrder();5336}5337}53385339/**5340* Returns a comparator that imposes the reverse ordering of the specified5341* comparator. If the specified comparator is {@code null}, this method is5342* equivalent to {@link #reverseOrder()} (in other words, it returns a5343* comparator that imposes the reverse of the <em>natural ordering</em> on5344* a collection of objects that implement the Comparable interface).5345*5346* <p>The returned comparator is serializable (assuming the specified5347* comparator is also serializable or {@code null}).5348*5349* @param <T> the class of the objects compared by the comparator5350* @param cmp a comparator who's ordering is to be reversed by the returned5351* comparator or {@code null}5352* @return A comparator that imposes the reverse ordering of the5353* specified comparator.5354* @since 1.55355*/5356@SuppressWarnings("unchecked")5357public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {5358if (cmp == null) {5359return (Comparator<T>) ReverseComparator.REVERSE_ORDER;5360} else if (cmp == ReverseComparator.REVERSE_ORDER) {5361return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;5362} else if (cmp == Comparators.NaturalOrderComparator.INSTANCE) {5363return (Comparator<T>) ReverseComparator.REVERSE_ORDER;5364} else if (cmp instanceof ReverseComparator2) {5365return ((ReverseComparator2<T>) cmp).cmp;5366} else {5367return new ReverseComparator2<>(cmp);5368}5369}53705371/**5372* @serial include5373*/5374private static class ReverseComparator2<T> implements Comparator<T>,5375Serializable5376{5377@java.io.Serial5378private static final long serialVersionUID = 4374092139857L;53795380/**5381* The comparator specified in the static factory. This will never5382* be null, as the static factory returns a ReverseComparator5383* instance if its argument is null.5384*5385* @serial5386*/5387@SuppressWarnings("serial") // Conditionally serializable5388final Comparator<T> cmp;53895390ReverseComparator2(Comparator<T> cmp) {5391assert cmp != null;5392this.cmp = cmp;5393}53945395public int compare(T t1, T t2) {5396return cmp.compare(t2, t1);5397}53985399public boolean equals(Object o) {5400return (o == this) ||5401(o instanceof ReverseComparator2 &&5402cmp.equals(((ReverseComparator2)o).cmp));5403}54045405public int hashCode() {5406return cmp.hashCode() ^ Integer.MIN_VALUE;5407}54085409@Override5410public Comparator<T> reversed() {5411return cmp;5412}5413}54145415/**5416* Returns an enumeration over the specified collection. This provides5417* interoperability with legacy APIs that require an enumeration5418* as input.5419*5420* <p>The iterator returned from a call to {@link Enumeration#asIterator()}5421* does not support removal of elements from the specified collection. This5422* is necessary to avoid unintentionally increasing the capabilities of the5423* returned enumeration.5424*5425* @param <T> the class of the objects in the collection5426* @param c the collection for which an enumeration is to be returned.5427* @return an enumeration over the specified collection.5428* @see Enumeration5429*/5430public static <T> Enumeration<T> enumeration(final Collection<T> c) {5431return new Enumeration<T>() {5432private final Iterator<T> i = c.iterator();54335434public boolean hasMoreElements() {5435return i.hasNext();5436}54375438public T nextElement() {5439return i.next();5440}5441};5442}54435444/**5445* Returns an array list containing the elements returned by the5446* specified enumeration in the order they are returned by the5447* enumeration. This method provides interoperability between5448* legacy APIs that return enumerations and new APIs that require5449* collections.5450*5451* @param <T> the class of the objects returned by the enumeration5452* @param e enumeration providing elements for the returned5453* array list5454* @return an array list containing the elements returned5455* by the specified enumeration.5456* @since 1.45457* @see Enumeration5458* @see ArrayList5459*/5460public static <T> ArrayList<T> list(Enumeration<T> e) {5461ArrayList<T> l = new ArrayList<>();5462while (e.hasMoreElements())5463l.add(e.nextElement());5464return l;5465}54665467/**5468* Returns true if the specified arguments are equal, or both null.5469*5470* NB: Do not replace with Object.equals until JDK-8015417 is resolved.5471*/5472static boolean eq(Object o1, Object o2) {5473return o1==null ? o2==null : o1.equals(o2);5474}54755476/**5477* Returns the number of elements in the specified collection equal to the5478* specified object. More formally, returns the number of elements5479* {@code e} in the collection such that5480* {@code Objects.equals(o, e)}.5481*5482* @param c the collection in which to determine the frequency5483* of {@code o}5484* @param o the object whose frequency is to be determined5485* @return the number of elements in {@code c} equal to {@code o}5486* @throws NullPointerException if {@code c} is null5487* @since 1.55488*/5489public static int frequency(Collection<?> c, Object o) {5490int result = 0;5491if (o == null) {5492for (Object e : c)5493if (e == null)5494result++;5495} else {5496for (Object e : c)5497if (o.equals(e))5498result++;5499}5500return result;5501}55025503/**5504* Returns {@code true} if the two specified collections have no5505* elements in common.5506*5507* <p>Care must be exercised if this method is used on collections that5508* do not comply with the general contract for {@code Collection}.5509* Implementations may elect to iterate over either collection and test5510* for containment in the other collection (or to perform any equivalent5511* computation). If either collection uses a nonstandard equality test5512* (as does a {@link SortedSet} whose ordering is not <em>compatible with5513* equals</em>, or the key set of an {@link IdentityHashMap}), both5514* collections must use the same nonstandard equality test, or the5515* result of this method is undefined.5516*5517* <p>Care must also be exercised when using collections that have5518* restrictions on the elements that they may contain. Collection5519* implementations are allowed to throw exceptions for any operation5520* involving elements they deem ineligible. For absolute safety the5521* specified collections should contain only elements which are5522* eligible elements for both collections.5523*5524* <p>Note that it is permissible to pass the same collection in both5525* parameters, in which case the method will return {@code true} if and5526* only if the collection is empty.5527*5528* @param c1 a collection5529* @param c2 a collection5530* @return {@code true} if the two specified collections have no5531* elements in common.5532* @throws NullPointerException if either collection is {@code null}.5533* @throws NullPointerException if one collection contains a {@code null}5534* element and {@code null} is not an eligible element for the other collection.5535* (<a href="Collection.html#optional-restrictions">optional</a>)5536* @throws ClassCastException if one collection contains an element that is5537* of a type which is ineligible for the other collection.5538* (<a href="Collection.html#optional-restrictions">optional</a>)5539* @since 1.55540*/5541public static boolean disjoint(Collection<?> c1, Collection<?> c2) {5542// The collection to be used for contains(). Preference is given to5543// the collection who's contains() has lower O() complexity.5544Collection<?> contains = c2;5545// The collection to be iterated. If the collections' contains() impl5546// are of different O() complexity, the collection with slower5547// contains() will be used for iteration. For collections who's5548// contains() are of the same complexity then best performance is5549// achieved by iterating the smaller collection.5550Collection<?> iterate = c1;55515552// Performance optimization cases. The heuristics:5553// 1. Generally iterate over c1.5554// 2. If c1 is a Set then iterate over c2.5555// 3. If either collection is empty then result is always true.5556// 4. Iterate over the smaller Collection.5557if (c1 instanceof Set) {5558// Use c1 for contains as a Set's contains() is expected to perform5559// better than O(N/2)5560iterate = c2;5561contains = c1;5562} else if (!(c2 instanceof Set)) {5563// Both are mere Collections. Iterate over smaller collection.5564// Example: If c1 contains 3 elements and c2 contains 50 elements and5565// assuming contains() requires ceiling(N/2) comparisons then5566// checking for all c1 elements in c2 would require 75 comparisons5567// (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring5568// 100 comparisons (50 * ceiling(3/2)).5569int c1size = c1.size();5570int c2size = c2.size();5571if (c1size == 0 || c2size == 0) {5572// At least one collection is empty. Nothing will match.5573return true;5574}55755576if (c1size > c2size) {5577iterate = c2;5578contains = c1;5579}5580}55815582for (Object e : iterate) {5583if (contains.contains(e)) {5584// Found a common element. Collections are not disjoint.5585return false;5586}5587}55885589// No common elements were found.5590return true;5591}55925593/**5594* Adds all of the specified elements to the specified collection.5595* Elements to be added may be specified individually or as an array.5596* The behaviour of this convenience method is similar to that of5597* {@code cc.addAll(Collections.unmodifiableList(Arrays.asList(elements)))}.5598*5599* <p>When elements are specified individually, this method provides a5600* convenient way to add a few elements to an existing collection:5601* <pre>5602* Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");5603* </pre>5604*5605* @param <T> the class of the elements to add and of the collection5606* @param c the collection into which {@code elements} are to be inserted5607* @param elements the elements to insert into {@code c}5608* @return {@code true} if the collection changed as a result of the call5609* @throws UnsupportedOperationException if {@code c} does not support5610* the {@code add} operation5611* @throws NullPointerException if {@code elements} contains one or more5612* null values and {@code c} does not permit null elements, or5613* if {@code c} or {@code elements} are {@code null}5614* @throws IllegalArgumentException if some property of a value in5615* {@code elements} prevents it from being added to {@code c}5616* @see Collection#addAll(Collection)5617* @since 1.55618*/5619@SafeVarargs5620public static <T> boolean addAll(Collection<? super T> c, T... elements) {5621boolean result = false;5622for (T element : elements)5623result |= c.add(element);5624return result;5625}56265627/**5628* Returns a set backed by the specified map. The resulting set displays5629* the same ordering, concurrency, and performance characteristics as the5630* backing map. In essence, this factory method provides a {@link Set}5631* implementation corresponding to any {@link Map} implementation. There5632* is no need to use this method on a {@link Map} implementation that5633* already has a corresponding {@link Set} implementation (such as {@link5634* HashMap} or {@link TreeMap}).5635*5636* <p>Each method invocation on the set returned by this method results in5637* exactly one method invocation on the backing map or its {@code keySet}5638* view, with one exception. The {@code addAll} method is implemented5639* as a sequence of {@code put} invocations on the backing map.5640*5641* <p>The specified map must be empty at the time this method is invoked,5642* and should not be accessed directly after this method returns. These5643* conditions are ensured if the map is created empty, passed directly5644* to this method, and no reference to the map is retained, as illustrated5645* in the following code fragment:5646* <pre>5647* Set<Object> weakHashSet = Collections.newSetFromMap(5648* new WeakHashMap<Object, Boolean>());5649* </pre>5650*5651* @param <E> the class of the map keys and of the objects in the5652* returned set5653* @param map the backing map5654* @return the set backed by the map5655* @throws IllegalArgumentException if {@code map} is not empty5656* @since 1.65657*/5658public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {5659return new SetFromMap<>(map);5660}56615662/**5663* @serial include5664*/5665private static class SetFromMap<E> extends AbstractSet<E>5666implements Set<E>, Serializable5667{5668@SuppressWarnings("serial") // Conditionally serializable5669private final Map<E, Boolean> m; // The backing map5670private transient Set<E> s; // Its keySet56715672SetFromMap(Map<E, Boolean> map) {5673if (!map.isEmpty())5674throw new IllegalArgumentException("Map is non-empty");5675m = map;5676s = map.keySet();5677}56785679public void clear() { m.clear(); }5680public int size() { return m.size(); }5681public boolean isEmpty() { return m.isEmpty(); }5682public boolean contains(Object o) { return m.containsKey(o); }5683public boolean remove(Object o) { return m.remove(o) != null; }5684public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }5685public Iterator<E> iterator() { return s.iterator(); }5686public Object[] toArray() { return s.toArray(); }5687public <T> T[] toArray(T[] a) { return s.toArray(a); }5688public String toString() { return s.toString(); }5689public int hashCode() { return s.hashCode(); }5690public boolean equals(Object o) { return o == this || s.equals(o); }5691public boolean containsAll(Collection<?> c) {return s.containsAll(c);}5692public boolean removeAll(Collection<?> c) {return s.removeAll(c);}5693public boolean retainAll(Collection<?> c) {return s.retainAll(c);}5694// addAll is the only inherited implementation56955696// Override default methods in Collection5697@Override5698public void forEach(Consumer<? super E> action) {5699s.forEach(action);5700}5701@Override5702public boolean removeIf(Predicate<? super E> filter) {5703return s.removeIf(filter);5704}57055706@Override5707public Spliterator<E> spliterator() {return s.spliterator();}5708@Override5709public Stream<E> stream() {return s.stream();}5710@Override5711public Stream<E> parallelStream() {return s.parallelStream();}57125713@java.io.Serial5714private static final long serialVersionUID = 2454657854757543876L;57155716@java.io.Serial5717private void readObject(java.io.ObjectInputStream stream)5718throws IOException, ClassNotFoundException5719{5720stream.defaultReadObject();5721s = m.keySet();5722}5723}57245725/**5726* Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)5727* {@link Queue}. Method {@code add} is mapped to {@code push},5728* {@code remove} is mapped to {@code pop} and so on. This5729* view can be useful when you would like to use a method5730* requiring a {@code Queue} but you need Lifo ordering.5731*5732* <p>Each method invocation on the queue returned by this method5733* results in exactly one method invocation on the backing deque, with5734* one exception. The {@link Queue#addAll addAll} method is5735* implemented as a sequence of {@link Deque#addFirst addFirst}5736* invocations on the backing deque.5737*5738* @param <T> the class of the objects in the deque5739* @param deque the deque5740* @return the queue5741* @since 1.65742*/5743public static <T> Queue<T> asLifoQueue(Deque<T> deque) {5744return new AsLIFOQueue<>(Objects.requireNonNull(deque));5745}57465747/**5748* @serial include5749*/5750static class AsLIFOQueue<E> extends AbstractQueue<E>5751implements Queue<E>, Serializable {5752@java.io.Serial5753private static final long serialVersionUID = 1802017725587941708L;5754@SuppressWarnings("serial") // Conditionally serializable5755private final Deque<E> q;5756AsLIFOQueue(Deque<E> q) { this.q = q; }5757public boolean add(E e) { q.addFirst(e); return true; }5758public boolean offer(E e) { return q.offerFirst(e); }5759public E poll() { return q.pollFirst(); }5760public E remove() { return q.removeFirst(); }5761public E peek() { return q.peekFirst(); }5762public E element() { return q.getFirst(); }5763public void clear() { q.clear(); }5764public int size() { return q.size(); }5765public boolean isEmpty() { return q.isEmpty(); }5766public boolean contains(Object o) { return q.contains(o); }5767public boolean remove(Object o) { return q.remove(o); }5768public Iterator<E> iterator() { return q.iterator(); }5769public Object[] toArray() { return q.toArray(); }5770public <T> T[] toArray(T[] a) { return q.toArray(a); }5771public <T> T[] toArray(IntFunction<T[]> f) { return q.toArray(f); }5772public String toString() { return q.toString(); }5773public boolean containsAll(Collection<?> c) { return q.containsAll(c); }5774public boolean removeAll(Collection<?> c) { return q.removeAll(c); }5775public boolean retainAll(Collection<?> c) { return q.retainAll(c); }5776// We use inherited addAll; forwarding addAll would be wrong57775778// Override default methods in Collection5779@Override5780public void forEach(Consumer<? super E> action) {q.forEach(action);}5781@Override5782public boolean removeIf(Predicate<? super E> filter) {5783return q.removeIf(filter);5784}5785@Override5786public Spliterator<E> spliterator() {return q.spliterator();}5787@Override5788public Stream<E> stream() {return q.stream();}5789@Override5790public Stream<E> parallelStream() {return q.parallelStream();}5791}5792}579357945795