Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/util/Collections.java
38829 views
/*1* Copyright (c) 1997, 2019, 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;26import java.io.Serializable;27import java.io.ObjectInputStream;28import java.io.ObjectOutputStream;29import java.io.IOException;30import java.lang.reflect.Array;31import java.util.function.BiConsumer;32import java.util.function.BiFunction;33import java.util.function.Consumer;34import java.util.function.Function;35import java.util.function.Predicate;36import java.util.function.UnaryOperator;37import java.util.stream.IntStream;38import java.util.stream.Stream;39import java.util.stream.StreamSupport;40import sun.misc.SharedSecrets;4142/**43* This class consists exclusively of static methods that operate on or return44* collections. It contains polymorphic algorithms that operate on45* collections, "wrappers", which return a new collection backed by a46* specified collection, and a few other odds and ends.47*48* <p>The methods of this class all throw a <tt>NullPointerException</tt>49* if the collections or class objects provided to them are null.50*51* <p>The documentation for the polymorphic algorithms contained in this class52* generally includes a brief description of the <i>implementation</i>. Such53* descriptions should be regarded as <i>implementation notes</i>, rather than54* parts of the <i>specification</i>. Implementors should feel free to55* substitute other algorithms, so long as the specification itself is adhered56* to. (For example, the algorithm used by <tt>sort</tt> does not have to be57* a mergesort, but it does have to be <i>stable</i>.)58*59* <p>The "destructive" algorithms contained in this class, that is, the60* algorithms that modify the collection on which they operate, are specified61* to throw <tt>UnsupportedOperationException</tt> if the collection does not62* support the appropriate mutation primitive(s), such as the <tt>set</tt>63* method. These algorithms may, but are not required to, throw this64* exception if an invocation would have no effect on the collection. For65* example, invoking the <tt>sort</tt> method on an unmodifiable list that is66* already sorted may or may not throw <tt>UnsupportedOperationException</tt>.67*68* <p>This class is a member of the69* <a href="{@docRoot}/../technotes/guides/collections/index.html">70* Java Collections Framework</a>.71*72* @author Josh Bloch73* @author Neal Gafter74* @see Collection75* @see Set76* @see List77* @see Map78* @since 1.279*/8081public class Collections {82// Suppresses default constructor, ensuring non-instantiability.83private Collections() {84}8586// Algorithms8788/*89* Tuning parameters for algorithms - Many of the List algorithms have90* two implementations, one of which is appropriate for RandomAccess91* lists, the other for "sequential." Often, the random access variant92* yields better performance on small sequential access lists. The93* tuning parameters below determine the cutoff point for what constitutes94* a "small" sequential access list for each algorithm. The values below95* were empirically determined to work well for LinkedList. Hopefully96* they should be reasonable for other sequential access List97* implementations. Those doing performance work on this code would98* do well to validate the values of these parameters from time to time.99* (The first word of each tuning parameter name is the algorithm to which100* it applies.)101*/102private static final int BINARYSEARCH_THRESHOLD = 5000;103private static final int REVERSE_THRESHOLD = 18;104private static final int SHUFFLE_THRESHOLD = 5;105private static final int FILL_THRESHOLD = 25;106private static final int ROTATE_THRESHOLD = 100;107private static final int COPY_THRESHOLD = 10;108private static final int REPLACEALL_THRESHOLD = 11;109private static final int INDEXOFSUBLIST_THRESHOLD = 35;110111/**112* Sorts the specified list into ascending order, according to the113* {@linkplain Comparable natural ordering} of its elements.114* All elements in the list must implement the {@link Comparable}115* interface. Furthermore, all elements in the list must be116* <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}117* must not throw a {@code ClassCastException} for any elements118* {@code e1} and {@code e2} in the list).119*120* <p>This sort is guaranteed to be <i>stable</i>: equal elements will121* not be reordered as a result of the sort.122*123* <p>The specified list must be modifiable, but need not be resizable.124*125* @implNote126* This implementation defers to the {@link List#sort(Comparator)}127* method using the specified list and a {@code null} comparator.128*129* @param <T> the class of the objects in the list130* @param list the list to be sorted.131* @throws ClassCastException if the list contains elements that are not132* <i>mutually comparable</i> (for example, strings and integers).133* @throws UnsupportedOperationException if the specified list's134* list-iterator does not support the {@code set} operation.135* @throws IllegalArgumentException (optional) if the implementation136* detects that the natural ordering of the list elements is137* found to violate the {@link Comparable} contract138* @see List#sort(Comparator)139*/140@SuppressWarnings("unchecked")141public static <T extends Comparable<? super T>> void sort(List<T> list) {142list.sort(null);143}144145/**146* Sorts the specified list according to the order induced by the147* specified comparator. All elements in the list must be <i>mutually148* comparable</i> using the specified comparator (that is,149* {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}150* for any elements {@code e1} and {@code e2} in the list).151*152* <p>This sort is guaranteed to be <i>stable</i>: equal elements will153* not be reordered as a result of the sort.154*155* <p>The specified list must be modifiable, but need not be resizable.156*157* @implNote158* This implementation defers to the {@link List#sort(Comparator)}159* method using the specified list and comparator.160*161* @param <T> the class of the objects in the list162* @param list the list to be sorted.163* @param c the comparator to determine the order of the list. A164* {@code null} value indicates that the elements' <i>natural165* ordering</i> should be used.166* @throws ClassCastException if the list contains elements that are not167* <i>mutually comparable</i> using the specified comparator.168* @throws UnsupportedOperationException if the specified list's169* list-iterator does not support the {@code set} operation.170* @throws IllegalArgumentException (optional) if the comparator is171* found to violate the {@link Comparator} contract172* @see List#sort(Comparator)173*/174@SuppressWarnings({"unchecked", "rawtypes"})175public static <T> void sort(List<T> list, Comparator<? super T> c) {176list.sort(c);177}178179180/**181* Searches the specified list for the specified object using the binary182* search algorithm. The list must be sorted into ascending order183* according to the {@linkplain Comparable natural ordering} of its184* elements (as by the {@link #sort(List)} method) prior to making this185* call. If it is not sorted, the results are undefined. If the list186* contains multiple elements equal to the specified object, there is no187* guarantee which one will be found.188*189* <p>This method runs in log(n) time for a "random access" list (which190* provides near-constant-time positional access). If the specified list191* does not implement the {@link RandomAccess} interface and is large,192* this method will do an iterator-based binary search that performs193* O(n) link traversals and O(log n) element comparisons.194*195* @param <T> the class of the objects in the list196* @param list the list to be searched.197* @param key the key to be searched for.198* @return the index of the search key, if it is contained in the list;199* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The200* <i>insertion point</i> is defined as the point at which the201* key would be inserted into the list: the index of the first202* element greater than the key, or <tt>list.size()</tt> if all203* elements in the list are less than the specified key. Note204* that this guarantees that the return value will be >= 0 if205* and only if the key is found.206* @throws ClassCastException if the list contains elements that are not207* <i>mutually comparable</i> (for example, strings and208* integers), or the search key is not mutually comparable209* with the elements of the list.210*/211public static <T>212int binarySearch(List<? extends Comparable<? super T>> list, T key) {213if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)214return Collections.indexedBinarySearch(list, key);215else216return Collections.iteratorBinarySearch(list, key);217}218219private static <T>220int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) {221int low = 0;222int high = list.size()-1;223224while (low <= high) {225int mid = (low + high) >>> 1;226Comparable<? super T> midVal = list.get(mid);227int cmp = midVal.compareTo(key);228229if (cmp < 0)230low = mid + 1;231else if (cmp > 0)232high = mid - 1;233else234return mid; // key found235}236return -(low + 1); // key not found237}238239private static <T>240int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key)241{242int low = 0;243int high = list.size()-1;244ListIterator<? extends Comparable<? super T>> i = list.listIterator();245246while (low <= high) {247int mid = (low + high) >>> 1;248Comparable<? super T> midVal = get(i, mid);249int cmp = midVal.compareTo(key);250251if (cmp < 0)252low = mid + 1;253else if (cmp > 0)254high = mid - 1;255else256return mid; // key found257}258return -(low + 1); // key not found259}260261/**262* Gets the ith element from the given list by repositioning the specified263* list listIterator.264*/265private static <T> T get(ListIterator<? extends T> i, int index) {266T obj = null;267int pos = i.nextIndex();268if (pos <= index) {269do {270obj = i.next();271} while (pos++ < index);272} else {273do {274obj = i.previous();275} while (--pos > index);276}277return obj;278}279280/**281* Searches the specified list for the specified object using the binary282* search algorithm. The list must be sorted into ascending order283* according to the specified comparator (as by the284* {@link #sort(List, Comparator) sort(List, Comparator)}285* method), prior to making this call. If it is286* not sorted, the results are undefined. If the list contains multiple287* elements equal to the specified object, there is no guarantee which one288* will be found.289*290* <p>This method runs in log(n) time for a "random access" list (which291* provides near-constant-time positional access). If the specified list292* does not implement the {@link RandomAccess} interface and is large,293* this method will do an iterator-based binary search that performs294* O(n) link traversals and O(log n) element comparisons.295*296* @param <T> the class of the objects in the list297* @param list the list to be searched.298* @param key the key to be searched for.299* @param c the comparator by which the list is ordered.300* A <tt>null</tt> value indicates that the elements'301* {@linkplain Comparable natural ordering} should be used.302* @return the index of the search key, if it is contained in the list;303* otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The304* <i>insertion point</i> is defined as the point at which the305* key would be inserted into the list: the index of the first306* element greater than the key, or <tt>list.size()</tt> if all307* elements in the list are less than the specified key. Note308* that this guarantees that the return value will be >= 0 if309* and only if the key is found.310* @throws ClassCastException if the list contains elements that are not311* <i>mutually comparable</i> using the specified comparator,312* or the search key is not mutually comparable with the313* elements of the list using this comparator.314*/315@SuppressWarnings("unchecked")316public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {317if (c==null)318return binarySearch((List<? extends Comparable<? super T>>) list, key);319320if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)321return Collections.indexedBinarySearch(list, key, c);322else323return Collections.iteratorBinarySearch(list, key, c);324}325326private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {327int low = 0;328int high = l.size()-1;329330while (low <= high) {331int mid = (low + high) >>> 1;332T midVal = l.get(mid);333int cmp = c.compare(midVal, key);334335if (cmp < 0)336low = mid + 1;337else if (cmp > 0)338high = mid - 1;339else340return mid; // key found341}342return -(low + 1); // key not found343}344345private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {346int low = 0;347int high = l.size()-1;348ListIterator<? extends T> i = l.listIterator();349350while (low <= high) {351int mid = (low + high) >>> 1;352T midVal = get(i, mid);353int cmp = c.compare(midVal, key);354355if (cmp < 0)356low = mid + 1;357else if (cmp > 0)358high = mid - 1;359else360return mid; // key found361}362return -(low + 1); // key not found363}364365/**366* Reverses the order of the elements in the specified list.<p>367*368* This method runs in linear time.369*370* @param list the list whose elements are to be reversed.371* @throws UnsupportedOperationException if the specified list or372* its list-iterator does not support the <tt>set</tt> operation.373*/374@SuppressWarnings({"rawtypes", "unchecked"})375public static void reverse(List<?> list) {376int size = list.size();377if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {378for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)379swap(list, i, j);380} else {381// instead of using a raw type here, it's possible to capture382// the wildcard but it will require a call to a supplementary383// private method384ListIterator fwd = list.listIterator();385ListIterator rev = list.listIterator(size);386for (int i=0, mid=list.size()>>1; i<mid; i++) {387Object tmp = fwd.next();388fwd.set(rev.previous());389rev.set(tmp);390}391}392}393394/**395* Randomly permutes the specified list using a default source of396* randomness. All permutations occur with approximately equal397* likelihood.398*399* <p>The hedge "approximately" is used in the foregoing description because400* default source of randomness is only approximately an unbiased source401* of independently chosen bits. If it were a perfect source of randomly402* chosen bits, then the algorithm would choose permutations with perfect403* uniformity.404*405* <p>This implementation traverses the list backwards, from the last406* element up to the second, repeatedly swapping a randomly selected element407* into the "current position". Elements are randomly selected from the408* portion of the list that runs from the first element to the current409* position, inclusive.410*411* <p>This method runs in linear time. If the specified list does not412* implement the {@link RandomAccess} interface and is large, this413* implementation dumps the specified list into an array before shuffling414* it, and dumps the shuffled array back into the list. This avoids the415* quadratic behavior that would result from shuffling a "sequential416* access" list in place.417*418* @param list the list to be shuffled.419* @throws UnsupportedOperationException if the specified list or420* its list-iterator does not support the <tt>set</tt> operation.421*/422public static void shuffle(List<?> list) {423Random rnd = r;424if (rnd == null)425r = rnd = new Random(); // harmless race.426shuffle(list, rnd);427}428429private static Random r;430431/**432* Randomly permute the specified list using the specified source of433* randomness. All permutations occur with equal likelihood434* assuming that the source of randomness is fair.<p>435*436* This implementation traverses the list backwards, from the last element437* up to the second, repeatedly swapping a randomly selected element into438* the "current position". Elements are randomly selected from the439* portion of the list that runs from the first element to the current440* position, inclusive.<p>441*442* This method runs in linear time. If the specified list does not443* implement the {@link RandomAccess} interface and is large, this444* implementation dumps the specified list into an array before shuffling445* it, and dumps the shuffled array back into the list. This avoids the446* quadratic behavior that would result from shuffling a "sequential447* access" list in place.448*449* @param list the list to be shuffled.450* @param rnd the source of randomness to use to shuffle the list.451* @throws UnsupportedOperationException if the specified list or its452* list-iterator does not support the <tt>set</tt> operation.453*/454@SuppressWarnings({"rawtypes", "unchecked"})455public static void shuffle(List<?> list, Random rnd) {456int size = list.size();457if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {458for (int i=size; i>1; i--)459swap(list, i-1, rnd.nextInt(i));460} else {461Object[] arr = list.toArray();462463// Shuffle array464for (int i=size; i>1; i--)465swap(arr, i-1, rnd.nextInt(i));466467// Dump array back into list468// instead of using a raw type here, it's possible to capture469// the wildcard but it will require a call to a supplementary470// private method471ListIterator it = list.listIterator();472for (int i=0; i<arr.length; i++) {473it.next();474it.set(arr[i]);475}476}477}478479/**480* Swaps the elements at the specified positions in the specified list.481* (If the specified positions are equal, invoking this method leaves482* the list unchanged.)483*484* @param list The list in which to swap elements.485* @param i the index of one element to be swapped.486* @param j the index of the other element to be swapped.487* @throws IndexOutOfBoundsException if either <tt>i</tt> or <tt>j</tt>488* is out of range (i < 0 || i >= list.size()489* || j < 0 || j >= list.size()).490* @since 1.4491*/492@SuppressWarnings({"rawtypes", "unchecked"})493public static void swap(List<?> list, int i, int j) {494// instead of using a raw type here, it's possible to capture495// the wildcard but it will require a call to a supplementary496// private method497final List l = list;498l.set(i, l.set(j, l.get(i)));499}500501/**502* Swaps the two specified elements in the specified array.503*/504private static void swap(Object[] arr, int i, int j) {505Object tmp = arr[i];506arr[i] = arr[j];507arr[j] = tmp;508}509510/**511* Replaces all of the elements of the specified list with the specified512* element. <p>513*514* This method runs in linear time.515*516* @param <T> the class of the objects in the list517* @param list the list to be filled with the specified element.518* @param obj The element with which to fill the specified list.519* @throws UnsupportedOperationException if the specified list or its520* list-iterator does not support the <tt>set</tt> operation.521*/522public static <T> void fill(List<? super T> list, T obj) {523int size = list.size();524525if (size < FILL_THRESHOLD || list instanceof RandomAccess) {526for (int i=0; i<size; i++)527list.set(i, obj);528} else {529ListIterator<? super T> itr = list.listIterator();530for (int i=0; i<size; i++) {531itr.next();532itr.set(obj);533}534}535}536537/**538* Copies all of the elements from one list into another. After the539* operation, the index of each copied element in the destination list540* will be identical to its index in the source list. The destination541* list must be at least as long as the source list. If it is longer, the542* remaining elements in the destination list are unaffected. <p>543*544* This method runs in linear time.545*546* @param <T> the class of the objects in the lists547* @param dest The destination list.548* @param src The source list.549* @throws IndexOutOfBoundsException if the destination list is too small550* to contain the entire source List.551* @throws UnsupportedOperationException if the destination list's552* list-iterator does not support the <tt>set</tt> operation.553*/554public static <T> void copy(List<? super T> dest, List<? extends T> src) {555int srcSize = src.size();556if (srcSize > dest.size())557throw new IndexOutOfBoundsException("Source does not fit in dest");558559if (srcSize < COPY_THRESHOLD ||560(src instanceof RandomAccess && dest instanceof RandomAccess)) {561for (int i=0; i<srcSize; i++)562dest.set(i, src.get(i));563} else {564ListIterator<? super T> di=dest.listIterator();565ListIterator<? extends T> si=src.listIterator();566for (int i=0; i<srcSize; i++) {567di.next();568di.set(si.next());569}570}571}572573/**574* Returns the minimum element of the given collection, according to the575* <i>natural ordering</i> of its elements. All elements in the576* collection must implement the <tt>Comparable</tt> interface.577* Furthermore, all elements in the collection must be <i>mutually578* comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a579* <tt>ClassCastException</tt> for any elements <tt>e1</tt> and580* <tt>e2</tt> in the collection).<p>581*582* This method iterates over the entire collection, hence it requires583* time proportional to the size of the collection.584*585* @param <T> the class of the objects in the collection586* @param coll the collection whose minimum element is to be determined.587* @return the minimum element of the given collection, according588* to the <i>natural ordering</i> of its elements.589* @throws ClassCastException if the collection contains elements that are590* not <i>mutually comparable</i> (for example, strings and591* integers).592* @throws NoSuchElementException if the collection is empty.593* @see Comparable594*/595public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {596Iterator<? extends T> i = coll.iterator();597T candidate = i.next();598599while (i.hasNext()) {600T next = i.next();601if (next.compareTo(candidate) < 0)602candidate = next;603}604return candidate;605}606607/**608* Returns the minimum element of the given collection, according to the609* order induced by the specified comparator. All elements in the610* collection must be <i>mutually comparable</i> by the specified611* comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a612* <tt>ClassCastException</tt> for any elements <tt>e1</tt> and613* <tt>e2</tt> in the collection).<p>614*615* This method iterates over the entire collection, hence it requires616* time proportional to the size of the collection.617*618* @param <T> the class of the objects in the collection619* @param coll the collection whose minimum element is to be determined.620* @param comp the comparator with which to determine the minimum element.621* A <tt>null</tt> value indicates that the elements' <i>natural622* ordering</i> should be used.623* @return the minimum element of the given collection, according624* to the specified comparator.625* @throws ClassCastException if the collection contains elements that are626* not <i>mutually comparable</i> using the specified comparator.627* @throws NoSuchElementException if the collection is empty.628* @see Comparable629*/630@SuppressWarnings({"unchecked", "rawtypes"})631public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {632if (comp==null)633return (T)min((Collection) coll);634635Iterator<? extends T> i = coll.iterator();636T candidate = i.next();637638while (i.hasNext()) {639T next = i.next();640if (comp.compare(next, candidate) < 0)641candidate = next;642}643return candidate;644}645646/**647* Returns the maximum element of the given collection, according to the648* <i>natural ordering</i> of its elements. All elements in the649* collection must implement the <tt>Comparable</tt> interface.650* Furthermore, all elements in the collection must be <i>mutually651* comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a652* <tt>ClassCastException</tt> for any elements <tt>e1</tt> and653* <tt>e2</tt> in the collection).<p>654*655* This method iterates over the entire collection, hence it requires656* time proportional to the size of the collection.657*658* @param <T> the class of the objects in the collection659* @param coll the collection whose maximum element is to be determined.660* @return the maximum element of the given collection, according661* to the <i>natural ordering</i> of its elements.662* @throws ClassCastException if the collection contains elements that are663* not <i>mutually comparable</i> (for example, strings and664* integers).665* @throws NoSuchElementException if the collection is empty.666* @see Comparable667*/668public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {669Iterator<? extends T> i = coll.iterator();670T candidate = i.next();671672while (i.hasNext()) {673T next = i.next();674if (next.compareTo(candidate) > 0)675candidate = next;676}677return candidate;678}679680/**681* Returns the maximum element of the given collection, according to the682* order induced by the specified comparator. All elements in the683* collection must be <i>mutually comparable</i> by the specified684* comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a685* <tt>ClassCastException</tt> for any elements <tt>e1</tt> and686* <tt>e2</tt> in the collection).<p>687*688* This method iterates over the entire collection, hence it requires689* time proportional to the size of the collection.690*691* @param <T> the class of the objects in the collection692* @param coll the collection whose maximum element is to be determined.693* @param comp the comparator with which to determine the maximum element.694* A <tt>null</tt> value indicates that the elements' <i>natural695* ordering</i> should be used.696* @return the maximum element of the given collection, according697* to the specified comparator.698* @throws ClassCastException if the collection contains elements that are699* not <i>mutually comparable</i> using the specified comparator.700* @throws NoSuchElementException if the collection is empty.701* @see Comparable702*/703@SuppressWarnings({"unchecked", "rawtypes"})704public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {705if (comp==null)706return (T)max((Collection) coll);707708Iterator<? extends T> i = coll.iterator();709T candidate = i.next();710711while (i.hasNext()) {712T next = i.next();713if (comp.compare(next, candidate) > 0)714candidate = next;715}716return candidate;717}718719/**720* Rotates the elements in the specified list by the specified distance.721* After calling this method, the element at index <tt>i</tt> will be722* the element previously at index <tt>(i - distance)</tt> mod723* <tt>list.size()</tt>, for all values of <tt>i</tt> between <tt>0</tt>724* and <tt>list.size()-1</tt>, inclusive. (This method has no effect on725* the size of the list.)726*727* <p>For example, suppose <tt>list</tt> comprises<tt> [t, a, n, k, s]</tt>.728* After invoking <tt>Collections.rotate(list, 1)</tt> (or729* <tt>Collections.rotate(list, -4)</tt>), <tt>list</tt> will comprise730* <tt>[s, t, a, n, k]</tt>.731*732* <p>Note that this method can usefully be applied to sublists to733* move one or more elements within a list while preserving the734* order of the remaining elements. For example, the following idiom735* moves the element at index <tt>j</tt> forward to position736* <tt>k</tt> (which must be greater than or equal to <tt>j</tt>):737* <pre>738* Collections.rotate(list.subList(j, k+1), -1);739* </pre>740* To make this concrete, suppose <tt>list</tt> comprises741* <tt>[a, b, c, d, e]</tt>. To move the element at index <tt>1</tt>742* (<tt>b</tt>) forward two positions, perform the following invocation:743* <pre>744* Collections.rotate(l.subList(1, 4), -1);745* </pre>746* The resulting list is <tt>[a, c, d, b, e]</tt>.747*748* <p>To move more than one element forward, increase the absolute value749* of the rotation distance. To move elements backward, use a positive750* shift distance.751*752* <p>If the specified list is small or implements the {@link753* RandomAccess} interface, this implementation exchanges the first754* element into the location it should go, and then repeatedly exchanges755* the displaced element into the location it should go until a displaced756* element is swapped into the first element. If necessary, the process757* is repeated on the second and successive elements, until the rotation758* is complete. If the specified list is large and doesn't implement the759* <tt>RandomAccess</tt> interface, this implementation breaks the760* list into two sublist views around index <tt>-distance mod size</tt>.761* Then the {@link #reverse(List)} method is invoked on each sublist view,762* and finally it is invoked on the entire list. For a more complete763* description of both algorithms, see Section 2.3 of Jon Bentley's764* <i>Programming Pearls</i> (Addison-Wesley, 1986).765*766* @param list the list to be rotated.767* @param distance the distance to rotate the list. There are no768* constraints on this value; it may be zero, negative, or769* greater than <tt>list.size()</tt>.770* @throws UnsupportedOperationException if the specified list or771* its list-iterator does not support the <tt>set</tt> operation.772* @since 1.4773*/774public static void rotate(List<?> list, int distance) {775if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)776rotate1(list, distance);777else778rotate2(list, distance);779}780781private static <T> void rotate1(List<T> list, int distance) {782int size = list.size();783if (size == 0)784return;785distance = distance % size;786if (distance < 0)787distance += size;788if (distance == 0)789return;790791for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {792T displaced = list.get(cycleStart);793int i = cycleStart;794do {795i += distance;796if (i >= size)797i -= size;798displaced = list.set(i, displaced);799nMoved ++;800} while (i != cycleStart);801}802}803804private static void rotate2(List<?> list, int distance) {805int size = list.size();806if (size == 0)807return;808int mid = -distance % size;809if (mid < 0)810mid += size;811if (mid == 0)812return;813814reverse(list.subList(0, mid));815reverse(list.subList(mid, size));816reverse(list);817}818819/**820* Replaces all occurrences of one specified value in a list with another.821* More formally, replaces with <tt>newVal</tt> each element <tt>e</tt>822* in <tt>list</tt> such that823* <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.824* (This method has no effect on the size of the list.)825*826* @param <T> the class of the objects in the list827* @param list the list in which replacement is to occur.828* @param oldVal the old value to be replaced.829* @param newVal the new value with which <tt>oldVal</tt> is to be830* replaced.831* @return <tt>true</tt> if <tt>list</tt> contained one or more elements832* <tt>e</tt> such that833* <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>.834* @throws UnsupportedOperationException if the specified list or835* its list-iterator does not support the <tt>set</tt> operation.836* @since 1.4837*/838public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {839boolean result = false;840int size = list.size();841if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {842if (oldVal==null) {843for (int i=0; i<size; i++) {844if (list.get(i)==null) {845list.set(i, newVal);846result = true;847}848}849} else {850for (int i=0; i<size; i++) {851if (oldVal.equals(list.get(i))) {852list.set(i, newVal);853result = true;854}855}856}857} else {858ListIterator<T> itr=list.listIterator();859if (oldVal==null) {860for (int i=0; i<size; i++) {861if (itr.next()==null) {862itr.set(newVal);863result = true;864}865}866} else {867for (int i=0; i<size; i++) {868if (oldVal.equals(itr.next())) {869itr.set(newVal);870result = true;871}872}873}874}875return result;876}877878/**879* Returns the starting position of the first occurrence of the specified880* target list within the specified source list, or -1 if there is no881* such occurrence. More formally, returns the lowest index <tt>i</tt>882* such that {@code source.subList(i, i+target.size()).equals(target)},883* or -1 if there is no such index. (Returns -1 if884* {@code target.size() > source.size()})885*886* <p>This implementation uses the "brute force" technique of scanning887* over the source list, looking for a match with the target at each888* location in turn.889*890* @param source the list in which to search for the first occurrence891* of <tt>target</tt>.892* @param target the list to search for as a subList of <tt>source</tt>.893* @return the starting position of the first occurrence of the specified894* target list within the specified source list, or -1 if there895* is no such occurrence.896* @since 1.4897*/898public static int indexOfSubList(List<?> source, List<?> target) {899int sourceSize = source.size();900int targetSize = target.size();901int maxCandidate = sourceSize - targetSize;902903if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||904(source instanceof RandomAccess&&target instanceof RandomAccess)) {905nextCand:906for (int candidate = 0; candidate <= maxCandidate; candidate++) {907for (int i=0, j=candidate; i<targetSize; i++, j++)908if (!eq(target.get(i), source.get(j)))909continue nextCand; // Element mismatch, try next cand910return candidate; // All elements of candidate matched target911}912} else { // Iterator version of above algorithm913ListIterator<?> si = source.listIterator();914nextCand:915for (int candidate = 0; candidate <= maxCandidate; candidate++) {916ListIterator<?> ti = target.listIterator();917for (int i=0; i<targetSize; i++) {918if (!eq(ti.next(), si.next())) {919// Back up source iterator to next candidate920for (int j=0; j<i; j++)921si.previous();922continue nextCand;923}924}925return candidate;926}927}928return -1; // No candidate matched the target929}930931/**932* Returns the starting position of the last occurrence of the specified933* target list within the specified source list, or -1 if there is no such934* occurrence. More formally, returns the highest index <tt>i</tt>935* such that {@code source.subList(i, i+target.size()).equals(target)},936* or -1 if there is no such index. (Returns -1 if937* {@code target.size() > source.size()})938*939* <p>This implementation uses the "brute force" technique of iterating940* over the source list, looking for a match with the target at each941* location in turn.942*943* @param source the list in which to search for the last occurrence944* of <tt>target</tt>.945* @param target the list to search for as a subList of <tt>source</tt>.946* @return the starting position of the last occurrence of the specified947* target list within the specified source list, or -1 if there948* is no such occurrence.949* @since 1.4950*/951public static int lastIndexOfSubList(List<?> source, List<?> target) {952int sourceSize = source.size();953int targetSize = target.size();954int maxCandidate = sourceSize - targetSize;955956if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||957source instanceof RandomAccess) { // Index access version958nextCand:959for (int candidate = maxCandidate; candidate >= 0; candidate--) {960for (int i=0, j=candidate; i<targetSize; i++, j++)961if (!eq(target.get(i), source.get(j)))962continue nextCand; // Element mismatch, try next cand963return candidate; // All elements of candidate matched target964}965} else { // Iterator version of above algorithm966if (maxCandidate < 0)967return -1;968ListIterator<?> si = source.listIterator(maxCandidate);969nextCand:970for (int candidate = maxCandidate; candidate >= 0; candidate--) {971ListIterator<?> ti = target.listIterator();972for (int i=0; i<targetSize; i++) {973if (!eq(ti.next(), si.next())) {974if (candidate != 0) {975// Back up source iterator to next candidate976for (int j=0; j<=i+1; j++)977si.previous();978}979continue nextCand;980}981}982return candidate;983}984}985return -1; // No candidate matched the target986}987988989// Unmodifiable Wrappers990991/**992* Returns an unmodifiable view of the specified collection. This method993* allows modules to provide users with "read-only" access to internal994* collections. Query operations on the returned collection "read through"995* to the specified collection, and attempts to modify the returned996* collection, whether direct or via its iterator, result in an997* <tt>UnsupportedOperationException</tt>.<p>998*999* The returned collection does <i>not</i> pass the hashCode and equals1000* operations through to the backing collection, but relies on1001* <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods. This1002* is necessary to preserve the contracts of these operations in the case1003* that the backing collection is a set or a list.<p>1004*1005* The returned collection will be serializable if the specified collection1006* is serializable.1007*1008* @param <T> the class of the objects in the collection1009* @param c the collection for which an unmodifiable view is to be1010* returned.1011* @return an unmodifiable view of the specified collection.1012*/1013public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {1014return new UnmodifiableCollection<>(c);1015}10161017/**1018* @serial include1019*/1020static class UnmodifiableCollection<E> implements Collection<E>, Serializable {1021private static final long serialVersionUID = 1820017752578914078L;10221023final Collection<? extends E> c;10241025UnmodifiableCollection(Collection<? extends E> c) {1026if (c==null)1027throw new NullPointerException();1028this.c = c;1029}10301031public int size() {return c.size();}1032public boolean isEmpty() {return c.isEmpty();}1033public boolean contains(Object o) {return c.contains(o);}1034public Object[] toArray() {return c.toArray();}1035public <T> T[] toArray(T[] a) {return c.toArray(a);}1036public String toString() {return c.toString();}10371038public Iterator<E> iterator() {1039return new Iterator<E>() {1040private final Iterator<? extends E> i = c.iterator();10411042public boolean hasNext() {return i.hasNext();}1043public E next() {return i.next();}1044public void remove() {1045throw new UnsupportedOperationException();1046}1047@Override1048public void forEachRemaining(Consumer<? super E> action) {1049// Use backing collection version1050i.forEachRemaining(action);1051}1052};1053}10541055public boolean add(E e) {1056throw new UnsupportedOperationException();1057}1058public boolean remove(Object o) {1059throw new UnsupportedOperationException();1060}10611062public boolean containsAll(Collection<?> coll) {1063return c.containsAll(coll);1064}1065public boolean addAll(Collection<? extends E> coll) {1066throw new UnsupportedOperationException();1067}1068public boolean removeAll(Collection<?> coll) {1069throw new UnsupportedOperationException();1070}1071public boolean retainAll(Collection<?> coll) {1072throw new UnsupportedOperationException();1073}1074public void clear() {1075throw new UnsupportedOperationException();1076}10771078// Override default methods in Collection1079@Override1080public void forEach(Consumer<? super E> action) {1081c.forEach(action);1082}1083@Override1084public boolean removeIf(Predicate<? super E> filter) {1085throw new UnsupportedOperationException();1086}1087@SuppressWarnings("unchecked")1088@Override1089public Spliterator<E> spliterator() {1090return (Spliterator<E>)c.spliterator();1091}1092@SuppressWarnings("unchecked")1093@Override1094public Stream<E> stream() {1095return (Stream<E>)c.stream();1096}1097@SuppressWarnings("unchecked")1098@Override1099public Stream<E> parallelStream() {1100return (Stream<E>)c.parallelStream();1101}1102}11031104/**1105* Returns an unmodifiable view of the specified set. This method allows1106* modules to provide users with "read-only" access to internal sets.1107* Query operations on the returned set "read through" to the specified1108* set, and attempts to modify the returned set, whether direct or via its1109* iterator, result in an <tt>UnsupportedOperationException</tt>.<p>1110*1111* The returned set will be serializable if the specified set1112* is serializable.1113*1114* @param <T> the class of the objects in the set1115* @param s the set for which an unmodifiable view is to be returned.1116* @return an unmodifiable view of the specified set.1117*/1118public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {1119return new UnmodifiableSet<>(s);1120}11211122/**1123* @serial include1124*/1125static class UnmodifiableSet<E> extends UnmodifiableCollection<E>1126implements Set<E>, Serializable {1127private static final long serialVersionUID = -9215047833775013803L;11281129UnmodifiableSet(Set<? extends E> s) {super(s);}1130public boolean equals(Object o) {return o == this || c.equals(o);}1131public int hashCode() {return c.hashCode();}1132}11331134/**1135* Returns an unmodifiable view of the specified sorted set. This method1136* allows modules to provide users with "read-only" access to internal1137* sorted sets. Query operations on the returned sorted set "read1138* through" to the specified sorted set. Attempts to modify the returned1139* sorted set, whether direct, via its iterator, or via its1140* <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in1141* an <tt>UnsupportedOperationException</tt>.<p>1142*1143* The returned sorted set will be serializable if the specified sorted set1144* is serializable.1145*1146* @param <T> the class of the objects in the set1147* @param s the sorted set for which an unmodifiable view is to be1148* returned.1149* @return an unmodifiable view of the specified sorted set.1150*/1151public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {1152return new UnmodifiableSortedSet<>(s);1153}11541155/**1156* @serial include1157*/1158static class UnmodifiableSortedSet<E>1159extends UnmodifiableSet<E>1160implements SortedSet<E>, Serializable {1161private static final long serialVersionUID = -4929149591599911165L;1162private final SortedSet<E> ss;11631164UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}11651166public Comparator<? super E> comparator() {return ss.comparator();}11671168public SortedSet<E> subSet(E fromElement, E toElement) {1169return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));1170}1171public SortedSet<E> headSet(E toElement) {1172return new UnmodifiableSortedSet<>(ss.headSet(toElement));1173}1174public SortedSet<E> tailSet(E fromElement) {1175return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));1176}11771178public E first() {return ss.first();}1179public E last() {return ss.last();}1180}11811182/**1183* Returns an unmodifiable view of the specified navigable set. This method1184* allows modules to provide users with "read-only" access to internal1185* navigable sets. Query operations on the returned navigable set "read1186* through" to the specified navigable set. Attempts to modify the returned1187* navigable set, whether direct, via its iterator, or via its1188* {@code subSet}, {@code headSet}, or {@code tailSet} views, result in1189* an {@code UnsupportedOperationException}.<p>1190*1191* The returned navigable set will be serializable if the specified1192* navigable set is serializable.1193*1194* @param <T> the class of the objects in the set1195* @param s the navigable set for which an unmodifiable view is to be1196* returned1197* @return an unmodifiable view of the specified navigable set1198* @since 1.81199*/1200public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) {1201return new UnmodifiableNavigableSet<>(s);1202}12031204/**1205* Wraps a navigable set and disables all of the mutative operations.1206*1207* @param <E> type of elements1208* @serial include1209*/1210static class UnmodifiableNavigableSet<E>1211extends UnmodifiableSortedSet<E>1212implements NavigableSet<E>, Serializable {12131214private static final long serialVersionUID = -6027448201786391929L;12151216/**1217* A singleton empty unmodifiable navigable set used for1218* {@link #emptyNavigableSet()}.1219*1220* @param <E> type of elements, if there were any, and bounds1221*/1222private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E>1223implements Serializable {1224private static final long serialVersionUID = -6291252904449939134L;12251226public EmptyNavigableSet() {1227super(new TreeSet<E>());1228}12291230private Object readResolve() { return EMPTY_NAVIGABLE_SET; }1231}12321233@SuppressWarnings("rawtypes")1234private static final NavigableSet<?> EMPTY_NAVIGABLE_SET =1235new EmptyNavigableSet<>();12361237/**1238* The instance we are protecting.1239*/1240private final NavigableSet<E> ns;12411242UnmodifiableNavigableSet(NavigableSet<E> s) {super(s); ns = s;}12431244public E lower(E e) { return ns.lower(e); }1245public E floor(E e) { return ns.floor(e); }1246public E ceiling(E e) { return ns.ceiling(e); }1247public E higher(E e) { return ns.higher(e); }1248public E pollFirst() { throw new UnsupportedOperationException(); }1249public E pollLast() { throw new UnsupportedOperationException(); }1250public NavigableSet<E> descendingSet()1251{ return new UnmodifiableNavigableSet<>(ns.descendingSet()); }1252public Iterator<E> descendingIterator()1253{ return descendingSet().iterator(); }12541255public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {1256return new UnmodifiableNavigableSet<>(1257ns.subSet(fromElement, fromInclusive, toElement, toInclusive));1258}12591260public NavigableSet<E> headSet(E toElement, boolean inclusive) {1261return new UnmodifiableNavigableSet<>(1262ns.headSet(toElement, inclusive));1263}12641265public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {1266return new UnmodifiableNavigableSet<>(1267ns.tailSet(fromElement, inclusive));1268}1269}12701271/**1272* Returns an unmodifiable view of the specified list. This method allows1273* modules to provide users with "read-only" access to internal1274* lists. Query operations on the returned list "read through" to the1275* specified list, and attempts to modify the returned list, whether1276* direct or via its iterator, result in an1277* <tt>UnsupportedOperationException</tt>.<p>1278*1279* The returned list will be serializable if the specified list1280* is serializable. Similarly, the returned list will implement1281* {@link RandomAccess} if the specified list does.1282*1283* @param <T> the class of the objects in the list1284* @param list the list for which an unmodifiable view is to be returned.1285* @return an unmodifiable view of the specified list.1286*/1287public static <T> List<T> unmodifiableList(List<? extends T> list) {1288return (list instanceof RandomAccess ?1289new UnmodifiableRandomAccessList<>(list) :1290new UnmodifiableList<>(list));1291}12921293/**1294* @serial include1295*/1296static class UnmodifiableList<E> extends UnmodifiableCollection<E>1297implements List<E> {1298private static final long serialVersionUID = -283967356065247728L;12991300final List<? extends E> list;13011302UnmodifiableList(List<? extends E> list) {1303super(list);1304this.list = list;1305}13061307public boolean equals(Object o) {return o == this || list.equals(o);}1308public int hashCode() {return list.hashCode();}13091310public E get(int index) {return list.get(index);}1311public E set(int index, E element) {1312throw new UnsupportedOperationException();1313}1314public void add(int index, E element) {1315throw new UnsupportedOperationException();1316}1317public E remove(int index) {1318throw new UnsupportedOperationException();1319}1320public int indexOf(Object o) {return list.indexOf(o);}1321public int lastIndexOf(Object o) {return list.lastIndexOf(o);}1322public boolean addAll(int index, Collection<? extends E> c) {1323throw new UnsupportedOperationException();1324}13251326@Override1327public void replaceAll(UnaryOperator<E> operator) {1328throw new UnsupportedOperationException();1329}1330@Override1331public void sort(Comparator<? super E> c) {1332throw new UnsupportedOperationException();1333}13341335public ListIterator<E> listIterator() {return listIterator(0);}13361337public ListIterator<E> listIterator(final int index) {1338return new ListIterator<E>() {1339private final ListIterator<? extends E> i1340= list.listIterator(index);13411342public boolean hasNext() {return i.hasNext();}1343public E next() {return i.next();}1344public boolean hasPrevious() {return i.hasPrevious();}1345public E previous() {return i.previous();}1346public int nextIndex() {return i.nextIndex();}1347public int previousIndex() {return i.previousIndex();}13481349public void remove() {1350throw new UnsupportedOperationException();1351}1352public void set(E e) {1353throw new UnsupportedOperationException();1354}1355public void add(E e) {1356throw new UnsupportedOperationException();1357}13581359@Override1360public void forEachRemaining(Consumer<? super E> action) {1361i.forEachRemaining(action);1362}1363};1364}13651366public List<E> subList(int fromIndex, int toIndex) {1367return new UnmodifiableList<>(list.subList(fromIndex, toIndex));1368}13691370/**1371* UnmodifiableRandomAccessList instances are serialized as1372* UnmodifiableList instances to allow them to be deserialized1373* in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).1374* This method inverts the transformation. As a beneficial1375* side-effect, it also grafts the RandomAccess marker onto1376* UnmodifiableList instances that were serialized in pre-1.4 JREs.1377*1378* Note: Unfortunately, UnmodifiableRandomAccessList instances1379* serialized in 1.4.1 and deserialized in 1.4 will become1380* UnmodifiableList instances, as this method was missing in 1.4.1381*/1382private Object readResolve() {1383return (list instanceof RandomAccess1384? new UnmodifiableRandomAccessList<>(list)1385: this);1386}1387}13881389/**1390* @serial include1391*/1392static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>1393implements RandomAccess1394{1395UnmodifiableRandomAccessList(List<? extends E> list) {1396super(list);1397}13981399public List<E> subList(int fromIndex, int toIndex) {1400return new UnmodifiableRandomAccessList<>(1401list.subList(fromIndex, toIndex));1402}14031404private static final long serialVersionUID = -2542308836966382001L;14051406/**1407* Allows instances to be deserialized in pre-1.4 JREs (which do1408* not have UnmodifiableRandomAccessList). UnmodifiableList has1409* a readResolve method that inverts this transformation upon1410* deserialization.1411*/1412private Object writeReplace() {1413return new UnmodifiableList<>(list);1414}1415}14161417/**1418* Returns an unmodifiable view of the specified map. This method1419* allows modules to provide users with "read-only" access to internal1420* maps. Query operations on the returned map "read through"1421* to the specified map, and attempts to modify the returned1422* map, whether direct or via its collection views, result in an1423* <tt>UnsupportedOperationException</tt>.<p>1424*1425* The returned map will be serializable if the specified map1426* is serializable.1427*1428* @param <K> the class of the map keys1429* @param <V> the class of the map values1430* @param m the map for which an unmodifiable view is to be returned.1431* @return an unmodifiable view of the specified map.1432*/1433public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {1434return new UnmodifiableMap<>(m);1435}14361437/**1438* @serial include1439*/1440private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {1441private static final long serialVersionUID = -1034234728574286014L;14421443private final Map<? extends K, ? extends V> m;14441445UnmodifiableMap(Map<? extends K, ? extends V> m) {1446if (m==null)1447throw new NullPointerException();1448this.m = m;1449}14501451public int size() {return m.size();}1452public boolean isEmpty() {return m.isEmpty();}1453public boolean containsKey(Object key) {return m.containsKey(key);}1454public boolean containsValue(Object val) {return m.containsValue(val);}1455public V get(Object key) {return m.get(key);}14561457public V put(K key, V value) {1458throw new UnsupportedOperationException();1459}1460public V remove(Object key) {1461throw new UnsupportedOperationException();1462}1463public void putAll(Map<? extends K, ? extends V> m) {1464throw new UnsupportedOperationException();1465}1466public void clear() {1467throw new UnsupportedOperationException();1468}14691470private transient Set<K> keySet;1471private transient Set<Map.Entry<K,V>> entrySet;1472private transient Collection<V> values;14731474public Set<K> keySet() {1475if (keySet==null)1476keySet = unmodifiableSet(m.keySet());1477return keySet;1478}14791480public Set<Map.Entry<K,V>> entrySet() {1481if (entrySet==null)1482entrySet = new UnmodifiableEntrySet<>(m.entrySet());1483return entrySet;1484}14851486public Collection<V> values() {1487if (values==null)1488values = unmodifiableCollection(m.values());1489return values;1490}14911492public boolean equals(Object o) {return o == this || m.equals(o);}1493public int hashCode() {return m.hashCode();}1494public String toString() {return m.toString();}14951496// Override default methods in Map1497@Override1498@SuppressWarnings("unchecked")1499public V getOrDefault(Object k, V defaultValue) {1500// Safe cast as we don't change the value1501return ((Map<K, V>)m).getOrDefault(k, defaultValue);1502}15031504@Override1505public void forEach(BiConsumer<? super K, ? super V> action) {1506m.forEach(action);1507}15081509@Override1510public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {1511throw new UnsupportedOperationException();1512}15131514@Override1515public V putIfAbsent(K key, V value) {1516throw new UnsupportedOperationException();1517}15181519@Override1520public boolean remove(Object key, Object value) {1521throw new UnsupportedOperationException();1522}15231524@Override1525public boolean replace(K key, V oldValue, V newValue) {1526throw new UnsupportedOperationException();1527}15281529@Override1530public V replace(K key, V value) {1531throw new UnsupportedOperationException();1532}15331534@Override1535public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {1536throw new UnsupportedOperationException();1537}15381539@Override1540public V computeIfPresent(K key,1541BiFunction<? super K, ? super V, ? extends V> remappingFunction) {1542throw new UnsupportedOperationException();1543}15441545@Override1546public V compute(K key,1547BiFunction<? super K, ? super V, ? extends V> remappingFunction) {1548throw new UnsupportedOperationException();1549}15501551@Override1552public V merge(K key, V value,1553BiFunction<? super V, ? super V, ? extends V> remappingFunction) {1554throw new UnsupportedOperationException();1555}15561557/**1558* We need this class in addition to UnmodifiableSet as1559* Map.Entries themselves permit modification of the backing Map1560* via their setValue operation. This class is subtle: there are1561* many possible attacks that must be thwarted.1562*1563* @serial include1564*/1565static class UnmodifiableEntrySet<K,V>1566extends UnmodifiableSet<Map.Entry<K,V>> {1567private static final long serialVersionUID = 7854390611657943733L;15681569@SuppressWarnings({"unchecked", "rawtypes"})1570UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {1571// Need to cast to raw in order to work around a limitation in the type system1572super((Set)s);1573}15741575static <K, V> Consumer<Map.Entry<K, V>> entryConsumer(Consumer<? super Entry<K, V>> action) {1576return e -> action.accept(new UnmodifiableEntry<>(e));1577}15781579public void forEach(Consumer<? super Entry<K, V>> action) {1580Objects.requireNonNull(action);1581c.forEach(entryConsumer(action));1582}15831584static final class UnmodifiableEntrySetSpliterator<K, V>1585implements Spliterator<Entry<K,V>> {1586final Spliterator<Map.Entry<K, V>> s;15871588UnmodifiableEntrySetSpliterator(Spliterator<Entry<K, V>> s) {1589this.s = s;1590}15911592@Override1593public boolean tryAdvance(Consumer<? super Entry<K, V>> action) {1594Objects.requireNonNull(action);1595return s.tryAdvance(entryConsumer(action));1596}15971598@Override1599public void forEachRemaining(Consumer<? super Entry<K, V>> action) {1600Objects.requireNonNull(action);1601s.forEachRemaining(entryConsumer(action));1602}16031604@Override1605public Spliterator<Entry<K, V>> trySplit() {1606Spliterator<Entry<K, V>> split = s.trySplit();1607return split == null1608? null1609: new UnmodifiableEntrySetSpliterator<>(split);1610}16111612@Override1613public long estimateSize() {1614return s.estimateSize();1615}16161617@Override1618public long getExactSizeIfKnown() {1619return s.getExactSizeIfKnown();1620}16211622@Override1623public int characteristics() {1624return s.characteristics();1625}16261627@Override1628public boolean hasCharacteristics(int characteristics) {1629return s.hasCharacteristics(characteristics);1630}16311632@Override1633public Comparator<? super Entry<K, V>> getComparator() {1634return s.getComparator();1635}1636}16371638@SuppressWarnings("unchecked")1639public Spliterator<Entry<K,V>> spliterator() {1640return new UnmodifiableEntrySetSpliterator<>(1641(Spliterator<Map.Entry<K, V>>) c.spliterator());1642}16431644@Override1645public Stream<Entry<K,V>> stream() {1646return StreamSupport.stream(spliterator(), false);1647}16481649@Override1650public Stream<Entry<K,V>> parallelStream() {1651return StreamSupport.stream(spliterator(), true);1652}16531654public Iterator<Map.Entry<K,V>> iterator() {1655return new Iterator<Map.Entry<K,V>>() {1656private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();16571658public boolean hasNext() {1659return i.hasNext();1660}1661public Map.Entry<K,V> next() {1662return new UnmodifiableEntry<>(i.next());1663}1664public void remove() {1665throw new UnsupportedOperationException();1666}1667};1668}16691670@SuppressWarnings("unchecked")1671public Object[] toArray() {1672Object[] a = c.toArray();1673for (int i=0; i<a.length; i++)1674a[i] = new UnmodifiableEntry<>((Map.Entry<? extends K, ? extends V>)a[i]);1675return a;1676}16771678@SuppressWarnings("unchecked")1679public <T> T[] toArray(T[] a) {1680// We don't pass a to c.toArray, to avoid window of1681// vulnerability wherein an unscrupulous multithreaded client1682// could get his hands on raw (unwrapped) Entries from c.1683Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));16841685for (int i=0; i<arr.length; i++)1686arr[i] = new UnmodifiableEntry<>((Map.Entry<? extends K, ? extends V>)arr[i]);16871688if (arr.length > a.length)1689return (T[])arr;16901691System.arraycopy(arr, 0, a, 0, arr.length);1692if (a.length > arr.length)1693a[arr.length] = null;1694return a;1695}16961697/**1698* This method is overridden to protect the backing set against1699* an object with a nefarious equals function that senses1700* that the equality-candidate is Map.Entry and calls its1701* setValue method.1702*/1703public boolean contains(Object o) {1704if (!(o instanceof Map.Entry))1705return false;1706return c.contains(1707new UnmodifiableEntry<>((Map.Entry<?,?>) o));1708}17091710/**1711* The next two methods are overridden to protect against1712* an unscrupulous List whose contains(Object o) method senses1713* when o is a Map.Entry, and calls o.setValue.1714*/1715public boolean containsAll(Collection<?> coll) {1716for (Object e : coll) {1717if (!contains(e)) // Invokes safe contains() above1718return false;1719}1720return true;1721}1722public boolean equals(Object o) {1723if (o == this)1724return true;17251726if (!(o instanceof Set))1727return false;1728Set<?> s = (Set<?>) o;1729if (s.size() != c.size())1730return false;1731return containsAll(s); // Invokes safe containsAll() above1732}17331734/**1735* This "wrapper class" serves two purposes: it prevents1736* the client from modifying the backing Map, by short-circuiting1737* the setValue method, and it protects the backing Map against1738* an ill-behaved Map.Entry that attempts to modify another1739* Map Entry when asked to perform an equality check.1740*/1741private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {1742private Map.Entry<? extends K, ? extends V> e;17431744UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e)1745{this.e = Objects.requireNonNull(e);}17461747public K getKey() {return e.getKey();}1748public V getValue() {return e.getValue();}1749public V setValue(V value) {1750throw new UnsupportedOperationException();1751}1752public int hashCode() {return e.hashCode();}1753public boolean equals(Object o) {1754if (this == o)1755return true;1756if (!(o instanceof Map.Entry))1757return false;1758Map.Entry<?,?> t = (Map.Entry<?,?>)o;1759return eq(e.getKey(), t.getKey()) &&1760eq(e.getValue(), t.getValue());1761}1762public String toString() {return e.toString();}1763}1764}1765}17661767/**1768* Returns an unmodifiable view of the specified sorted map. This method1769* allows modules to provide users with "read-only" access to internal1770* sorted maps. Query operations on the returned sorted map "read through"1771* to the specified sorted map. Attempts to modify the returned1772* sorted map, whether direct, via its collection views, or via its1773* <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in1774* an <tt>UnsupportedOperationException</tt>.<p>1775*1776* The returned sorted map will be serializable if the specified sorted map1777* is serializable.1778*1779* @param <K> the class of the map keys1780* @param <V> the class of the map values1781* @param m the sorted map for which an unmodifiable view is to be1782* returned.1783* @return an unmodifiable view of the specified sorted map.1784*/1785public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {1786return new UnmodifiableSortedMap<>(m);1787}17881789/**1790* @serial include1791*/1792static class UnmodifiableSortedMap<K,V>1793extends UnmodifiableMap<K,V>1794implements SortedMap<K,V>, Serializable {1795private static final long serialVersionUID = -8806743815996713206L;17961797private final SortedMap<K, ? extends V> sm;17981799UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m; }1800public Comparator<? super K> comparator() { return sm.comparator(); }1801public SortedMap<K,V> subMap(K fromKey, K toKey)1802{ return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); }1803public SortedMap<K,V> headMap(K toKey)1804{ return new UnmodifiableSortedMap<>(sm.headMap(toKey)); }1805public SortedMap<K,V> tailMap(K fromKey)1806{ return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); }1807public K firstKey() { return sm.firstKey(); }1808public K lastKey() { return sm.lastKey(); }1809}18101811/**1812* Returns an unmodifiable view of the specified navigable map. This method1813* allows modules to provide users with "read-only" access to internal1814* navigable maps. Query operations on the returned navigable map "read1815* through" to the specified navigable map. Attempts to modify the returned1816* navigable map, whether direct, via its collection views, or via its1817* {@code subMap}, {@code headMap}, or {@code tailMap} views, result in1818* an {@code UnsupportedOperationException}.<p>1819*1820* The returned navigable map will be serializable if the specified1821* navigable map is serializable.1822*1823* @param <K> the class of the map keys1824* @param <V> the class of the map values1825* @param m the navigable map for which an unmodifiable view is to be1826* returned1827* @return an unmodifiable view of the specified navigable map1828* @since 1.81829*/1830public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {1831return new UnmodifiableNavigableMap<>(m);1832}18331834/**1835* @serial include1836*/1837static class UnmodifiableNavigableMap<K,V>1838extends UnmodifiableSortedMap<K,V>1839implements NavigableMap<K,V>, Serializable {1840private static final long serialVersionUID = -4858195264774772197L;18411842/**1843* A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve1844* to preserve singleton property.1845*1846* @param <K> type of keys, if there were any, and of bounds1847* @param <V> type of values, if there were any1848*/1849private static class EmptyNavigableMap<K,V> extends UnmodifiableNavigableMap<K,V>1850implements Serializable {18511852private static final long serialVersionUID = -2239321462712562324L;18531854EmptyNavigableMap() { super(new TreeMap<K,V>()); }18551856@Override1857public NavigableSet<K> navigableKeySet()1858{ return emptyNavigableSet(); }18591860private Object readResolve() { return EMPTY_NAVIGABLE_MAP; }1861}18621863/**1864* Singleton for {@link emptyNavigableMap()} which is also immutable.1865*/1866private static final EmptyNavigableMap<?,?> EMPTY_NAVIGABLE_MAP =1867new EmptyNavigableMap<>();18681869/**1870* The instance we wrap and protect.1871*/1872private final NavigableMap<K, ? extends V> nm;18731874UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m)1875{super(m); nm = m;}18761877public K lowerKey(K key) { return nm.lowerKey(key); }1878public K floorKey(K key) { return nm.floorKey(key); }1879public K ceilingKey(K key) { return nm.ceilingKey(key); }1880public K higherKey(K key) { return nm.higherKey(key); }18811882@SuppressWarnings("unchecked")1883public Entry<K, V> lowerEntry(K key) {1884Entry<K,V> lower = (Entry<K, V>) nm.lowerEntry(key);1885return (null != lower)1886? new UnmodifiableEntrySet.UnmodifiableEntry<>(lower)1887: null;1888}18891890@SuppressWarnings("unchecked")1891public Entry<K, V> floorEntry(K key) {1892Entry<K,V> floor = (Entry<K, V>) nm.floorEntry(key);1893return (null != floor)1894? new UnmodifiableEntrySet.UnmodifiableEntry<>(floor)1895: null;1896}18971898@SuppressWarnings("unchecked")1899public Entry<K, V> ceilingEntry(K key) {1900Entry<K,V> ceiling = (Entry<K, V>) nm.ceilingEntry(key);1901return (null != ceiling)1902? new UnmodifiableEntrySet.UnmodifiableEntry<>(ceiling)1903: null;1904}190519061907@SuppressWarnings("unchecked")1908public Entry<K, V> higherEntry(K key) {1909Entry<K,V> higher = (Entry<K, V>) nm.higherEntry(key);1910return (null != higher)1911? new UnmodifiableEntrySet.UnmodifiableEntry<>(higher)1912: null;1913}19141915@SuppressWarnings("unchecked")1916public Entry<K, V> firstEntry() {1917Entry<K,V> first = (Entry<K, V>) nm.firstEntry();1918return (null != first)1919? new UnmodifiableEntrySet.UnmodifiableEntry<>(first)1920: null;1921}19221923@SuppressWarnings("unchecked")1924public Entry<K, V> lastEntry() {1925Entry<K,V> last = (Entry<K, V>) nm.lastEntry();1926return (null != last)1927? new UnmodifiableEntrySet.UnmodifiableEntry<>(last)1928: null;1929}19301931public Entry<K, V> pollFirstEntry()1932{ throw new UnsupportedOperationException(); }1933public Entry<K, V> pollLastEntry()1934{ throw new UnsupportedOperationException(); }1935public NavigableMap<K, V> descendingMap()1936{ return unmodifiableNavigableMap(nm.descendingMap()); }1937public NavigableSet<K> navigableKeySet()1938{ return unmodifiableNavigableSet(nm.navigableKeySet()); }1939public NavigableSet<K> descendingKeySet()1940{ return unmodifiableNavigableSet(nm.descendingKeySet()); }19411942public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {1943return unmodifiableNavigableMap(1944nm.subMap(fromKey, fromInclusive, toKey, toInclusive));1945}19461947public NavigableMap<K, V> headMap(K toKey, boolean inclusive)1948{ return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); }1949public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)1950{ return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); }1951}19521953// Synch Wrappers19541955/**1956* Returns a synchronized (thread-safe) collection backed by the specified1957* collection. In order to guarantee serial access, it is critical that1958* <strong>all</strong> access to the backing collection is accomplished1959* through the returned collection.<p>1960*1961* It is imperative that the user manually synchronize on the returned1962* collection when traversing it via {@link Iterator}, {@link Spliterator}1963* or {@link Stream}:1964* <pre>1965* Collection c = Collections.synchronizedCollection(myCollection);1966* ...1967* synchronized (c) {1968* Iterator i = c.iterator(); // Must be in the synchronized block1969* while (i.hasNext())1970* foo(i.next());1971* }1972* </pre>1973* Failure to follow this advice may result in non-deterministic behavior.1974*1975* <p>The returned collection does <i>not</i> pass the {@code hashCode}1976* and {@code equals} operations through to the backing collection, but1977* relies on {@code Object}'s equals and hashCode methods. This is1978* necessary to preserve the contracts of these operations in the case1979* that the backing collection is a set or a list.<p>1980*1981* The returned collection will be serializable if the specified collection1982* is serializable.1983*1984* @param <T> the class of the objects in the collection1985* @param c the collection to be "wrapped" in a synchronized collection.1986* @return a synchronized view of the specified collection.1987*/1988public static <T> Collection<T> synchronizedCollection(Collection<T> c) {1989return new SynchronizedCollection<>(c);1990}19911992static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {1993return new SynchronizedCollection<>(c, mutex);1994}19951996/**1997* @serial include1998*/1999static class SynchronizedCollection<E> implements Collection<E>, Serializable {2000private static final long serialVersionUID = 3053995032091335093L;20012002final Collection<E> c; // Backing Collection2003final Object mutex; // Object on which to synchronize20042005SynchronizedCollection(Collection<E> c) {2006this.c = Objects.requireNonNull(c);2007mutex = this;2008}20092010SynchronizedCollection(Collection<E> c, Object mutex) {2011this.c = Objects.requireNonNull(c);2012this.mutex = Objects.requireNonNull(mutex);2013}20142015public int size() {2016synchronized (mutex) {return c.size();}2017}2018public boolean isEmpty() {2019synchronized (mutex) {return c.isEmpty();}2020}2021public boolean contains(Object o) {2022synchronized (mutex) {return c.contains(o);}2023}2024public Object[] toArray() {2025synchronized (mutex) {return c.toArray();}2026}2027public <T> T[] toArray(T[] a) {2028synchronized (mutex) {return c.toArray(a);}2029}20302031public Iterator<E> iterator() {2032return c.iterator(); // Must be manually synched by user!2033}20342035public boolean add(E e) {2036synchronized (mutex) {return c.add(e);}2037}2038public boolean remove(Object o) {2039synchronized (mutex) {return c.remove(o);}2040}20412042public boolean containsAll(Collection<?> coll) {2043synchronized (mutex) {return c.containsAll(coll);}2044}2045public boolean addAll(Collection<? extends E> coll) {2046synchronized (mutex) {return c.addAll(coll);}2047}2048public boolean removeAll(Collection<?> coll) {2049synchronized (mutex) {return c.removeAll(coll);}2050}2051public boolean retainAll(Collection<?> coll) {2052synchronized (mutex) {return c.retainAll(coll);}2053}2054public void clear() {2055synchronized (mutex) {c.clear();}2056}2057public String toString() {2058synchronized (mutex) {return c.toString();}2059}2060// Override default methods in Collection2061@Override2062public void forEach(Consumer<? super E> consumer) {2063synchronized (mutex) {c.forEach(consumer);}2064}2065@Override2066public boolean removeIf(Predicate<? super E> filter) {2067synchronized (mutex) {return c.removeIf(filter);}2068}2069@Override2070public Spliterator<E> spliterator() {2071return c.spliterator(); // Must be manually synched by user!2072}2073@Override2074public Stream<E> stream() {2075return c.stream(); // Must be manually synched by user!2076}2077@Override2078public Stream<E> parallelStream() {2079return c.parallelStream(); // Must be manually synched by user!2080}2081private void writeObject(ObjectOutputStream s) throws IOException {2082synchronized (mutex) {s.defaultWriteObject();}2083}2084}20852086/**2087* Returns a synchronized (thread-safe) set backed by the specified2088* set. In order to guarantee serial access, it is critical that2089* <strong>all</strong> access to the backing set is accomplished2090* through the returned set.<p>2091*2092* It is imperative that the user manually synchronize on the returned2093* set when iterating over it:2094* <pre>2095* Set s = Collections.synchronizedSet(new HashSet());2096* ...2097* synchronized (s) {2098* Iterator i = s.iterator(); // Must be in the synchronized block2099* while (i.hasNext())2100* foo(i.next());2101* }2102* </pre>2103* Failure to follow this advice may result in non-deterministic behavior.2104*2105* <p>The returned set will be serializable if the specified set is2106* serializable.2107*2108* @param <T> the class of the objects in the set2109* @param s the set to be "wrapped" in a synchronized set.2110* @return a synchronized view of the specified set.2111*/2112public static <T> Set<T> synchronizedSet(Set<T> s) {2113return new SynchronizedSet<>(s);2114}21152116static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {2117return new SynchronizedSet<>(s, mutex);2118}21192120/**2121* @serial include2122*/2123static class SynchronizedSet<E>2124extends SynchronizedCollection<E>2125implements Set<E> {2126private static final long serialVersionUID = 487447009682186044L;21272128SynchronizedSet(Set<E> s) {2129super(s);2130}2131SynchronizedSet(Set<E> s, Object mutex) {2132super(s, mutex);2133}21342135public boolean equals(Object o) {2136if (this == o)2137return true;2138synchronized (mutex) {return c.equals(o);}2139}2140public int hashCode() {2141synchronized (mutex) {return c.hashCode();}2142}2143}21442145/**2146* Returns a synchronized (thread-safe) sorted set backed by the specified2147* sorted set. In order to guarantee serial access, it is critical that2148* <strong>all</strong> access to the backing sorted set is accomplished2149* through the returned sorted set (or its views).<p>2150*2151* It is imperative that the user manually synchronize on the returned2152* sorted set when iterating over it or any of its <tt>subSet</tt>,2153* <tt>headSet</tt>, or <tt>tailSet</tt> views.2154* <pre>2155* SortedSet s = Collections.synchronizedSortedSet(new TreeSet());2156* ...2157* synchronized (s) {2158* Iterator i = s.iterator(); // Must be in the synchronized block2159* while (i.hasNext())2160* foo(i.next());2161* }2162* </pre>2163* or:2164* <pre>2165* SortedSet s = Collections.synchronizedSortedSet(new TreeSet());2166* SortedSet s2 = s.headSet(foo);2167* ...2168* synchronized (s) { // Note: s, not s2!!!2169* Iterator i = s2.iterator(); // Must be in the synchronized block2170* while (i.hasNext())2171* foo(i.next());2172* }2173* </pre>2174* Failure to follow this advice may result in non-deterministic behavior.2175*2176* <p>The returned sorted set will be serializable if the specified2177* sorted set is serializable.2178*2179* @param <T> the class of the objects in the set2180* @param s the sorted set to be "wrapped" in a synchronized sorted set.2181* @return a synchronized view of the specified sorted set.2182*/2183public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {2184return new SynchronizedSortedSet<>(s);2185}21862187/**2188* @serial include2189*/2190static class SynchronizedSortedSet<E>2191extends SynchronizedSet<E>2192implements SortedSet<E>2193{2194private static final long serialVersionUID = 8695801310862127406L;21952196private final SortedSet<E> ss;21972198SynchronizedSortedSet(SortedSet<E> s) {2199super(s);2200ss = s;2201}2202SynchronizedSortedSet(SortedSet<E> s, Object mutex) {2203super(s, mutex);2204ss = s;2205}22062207public Comparator<? super E> comparator() {2208synchronized (mutex) {return ss.comparator();}2209}22102211public SortedSet<E> subSet(E fromElement, E toElement) {2212synchronized (mutex) {2213return new SynchronizedSortedSet<>(2214ss.subSet(fromElement, toElement), mutex);2215}2216}2217public SortedSet<E> headSet(E toElement) {2218synchronized (mutex) {2219return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);2220}2221}2222public SortedSet<E> tailSet(E fromElement) {2223synchronized (mutex) {2224return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);2225}2226}22272228public E first() {2229synchronized (mutex) {return ss.first();}2230}2231public E last() {2232synchronized (mutex) {return ss.last();}2233}2234}22352236/**2237* Returns a synchronized (thread-safe) navigable set backed by the2238* specified navigable set. In order to guarantee serial access, it is2239* critical that <strong>all</strong> access to the backing navigable set is2240* accomplished through the returned navigable set (or its views).<p>2241*2242* It is imperative that the user manually synchronize on the returned2243* navigable set when iterating over it or any of its {@code subSet},2244* {@code headSet}, or {@code tailSet} views.2245* <pre>2246* NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());2247* ...2248* synchronized (s) {2249* Iterator i = s.iterator(); // Must be in the synchronized block2250* while (i.hasNext())2251* foo(i.next());2252* }2253* </pre>2254* or:2255* <pre>2256* NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());2257* NavigableSet s2 = s.headSet(foo, true);2258* ...2259* synchronized (s) { // Note: s, not s2!!!2260* Iterator i = s2.iterator(); // Must be in the synchronized block2261* while (i.hasNext())2262* foo(i.next());2263* }2264* </pre>2265* Failure to follow this advice may result in non-deterministic behavior.2266*2267* <p>The returned navigable set will be serializable if the specified2268* navigable set is serializable.2269*2270* @param <T> the class of the objects in the set2271* @param s the navigable set to be "wrapped" in a synchronized navigable2272* set2273* @return a synchronized view of the specified navigable set2274* @since 1.82275*/2276public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) {2277return new SynchronizedNavigableSet<>(s);2278}22792280/**2281* @serial include2282*/2283static class SynchronizedNavigableSet<E>2284extends SynchronizedSortedSet<E>2285implements NavigableSet<E>2286{2287private static final long serialVersionUID = -5505529816273629798L;22882289private final NavigableSet<E> ns;22902291SynchronizedNavigableSet(NavigableSet<E> s) {2292super(s);2293ns = s;2294}22952296SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) {2297super(s, mutex);2298ns = s;2299}2300public E lower(E e) { synchronized (mutex) {return ns.lower(e);} }2301public E floor(E e) { synchronized (mutex) {return ns.floor(e);} }2302public E ceiling(E e) { synchronized (mutex) {return ns.ceiling(e);} }2303public E higher(E e) { synchronized (mutex) {return ns.higher(e);} }2304public E pollFirst() { synchronized (mutex) {return ns.pollFirst();} }2305public E pollLast() { synchronized (mutex) {return ns.pollLast();} }23062307public NavigableSet<E> descendingSet() {2308synchronized (mutex) {2309return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex);2310}2311}23122313public Iterator<E> descendingIterator()2314{ synchronized (mutex) { return descendingSet().iterator(); } }23152316public NavigableSet<E> subSet(E fromElement, E toElement) {2317synchronized (mutex) {2318return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex);2319}2320}2321public NavigableSet<E> headSet(E toElement) {2322synchronized (mutex) {2323return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex);2324}2325}2326public NavigableSet<E> tailSet(E fromElement) {2327synchronized (mutex) {2328return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, true), mutex);2329}2330}23312332public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {2333synchronized (mutex) {2334return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex);2335}2336}23372338public NavigableSet<E> headSet(E toElement, boolean inclusive) {2339synchronized (mutex) {2340return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex);2341}2342}23432344public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {2345synchronized (mutex) {2346return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive), mutex);2347}2348}2349}23502351/**2352* Returns a synchronized (thread-safe) list backed by the specified2353* list. In order to guarantee serial access, it is critical that2354* <strong>all</strong> access to the backing list is accomplished2355* through the returned list.<p>2356*2357* It is imperative that the user manually synchronize on the returned2358* list when iterating over it:2359* <pre>2360* List list = Collections.synchronizedList(new ArrayList());2361* ...2362* synchronized (list) {2363* Iterator i = list.iterator(); // Must be in synchronized block2364* while (i.hasNext())2365* foo(i.next());2366* }2367* </pre>2368* Failure to follow this advice may result in non-deterministic behavior.2369*2370* <p>The returned list will be serializable if the specified list is2371* serializable.2372*2373* @param <T> the class of the objects in the list2374* @param list the list to be "wrapped" in a synchronized list.2375* @return a synchronized view of the specified list.2376*/2377public static <T> List<T> synchronizedList(List<T> list) {2378return (list instanceof RandomAccess ?2379new SynchronizedRandomAccessList<>(list) :2380new SynchronizedList<>(list));2381}23822383static <T> List<T> synchronizedList(List<T> list, Object mutex) {2384return (list instanceof RandomAccess ?2385new SynchronizedRandomAccessList<>(list, mutex) :2386new SynchronizedList<>(list, mutex));2387}23882389/**2390* @serial include2391*/2392static class SynchronizedList<E>2393extends SynchronizedCollection<E>2394implements List<E> {2395private static final long serialVersionUID = -7754090372962971524L;23962397final List<E> list;23982399SynchronizedList(List<E> list) {2400super(list);2401this.list = list;2402}2403SynchronizedList(List<E> list, Object mutex) {2404super(list, mutex);2405this.list = list;2406}24072408public boolean equals(Object o) {2409if (this == o)2410return true;2411synchronized (mutex) {return list.equals(o);}2412}2413public int hashCode() {2414synchronized (mutex) {return list.hashCode();}2415}24162417public E get(int index) {2418synchronized (mutex) {return list.get(index);}2419}2420public E set(int index, E element) {2421synchronized (mutex) {return list.set(index, element);}2422}2423public void add(int index, E element) {2424synchronized (mutex) {list.add(index, element);}2425}2426public E remove(int index) {2427synchronized (mutex) {return list.remove(index);}2428}24292430public int indexOf(Object o) {2431synchronized (mutex) {return list.indexOf(o);}2432}2433public int lastIndexOf(Object o) {2434synchronized (mutex) {return list.lastIndexOf(o);}2435}24362437public boolean addAll(int index, Collection<? extends E> c) {2438synchronized (mutex) {return list.addAll(index, c);}2439}24402441public ListIterator<E> listIterator() {2442return list.listIterator(); // Must be manually synched by user2443}24442445public ListIterator<E> listIterator(int index) {2446return list.listIterator(index); // Must be manually synched by user2447}24482449public List<E> subList(int fromIndex, int toIndex) {2450synchronized (mutex) {2451return new SynchronizedList<>(list.subList(fromIndex, toIndex),2452mutex);2453}2454}24552456@Override2457public void replaceAll(UnaryOperator<E> operator) {2458synchronized (mutex) {list.replaceAll(operator);}2459}2460@Override2461public void sort(Comparator<? super E> c) {2462synchronized (mutex) {list.sort(c);}2463}24642465/**2466* SynchronizedRandomAccessList instances are serialized as2467* SynchronizedList instances to allow them to be deserialized2468* in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).2469* This method inverts the transformation. As a beneficial2470* side-effect, it also grafts the RandomAccess marker onto2471* SynchronizedList instances that were serialized in pre-1.4 JREs.2472*2473* Note: Unfortunately, SynchronizedRandomAccessList instances2474* serialized in 1.4.1 and deserialized in 1.4 will become2475* SynchronizedList instances, as this method was missing in 1.4.2476*/2477private Object readResolve() {2478return (list instanceof RandomAccess2479? new SynchronizedRandomAccessList<>(list)2480: this);2481}2482}24832484/**2485* @serial include2486*/2487static class SynchronizedRandomAccessList<E>2488extends SynchronizedList<E>2489implements RandomAccess {24902491SynchronizedRandomAccessList(List<E> list) {2492super(list);2493}24942495SynchronizedRandomAccessList(List<E> list, Object mutex) {2496super(list, mutex);2497}24982499public List<E> subList(int fromIndex, int toIndex) {2500synchronized (mutex) {2501return new SynchronizedRandomAccessList<>(2502list.subList(fromIndex, toIndex), mutex);2503}2504}25052506private static final long serialVersionUID = 1530674583602358482L;25072508/**2509* Allows instances to be deserialized in pre-1.4 JREs (which do2510* not have SynchronizedRandomAccessList). SynchronizedList has2511* a readResolve method that inverts this transformation upon2512* deserialization.2513*/2514private Object writeReplace() {2515return new SynchronizedList<>(list);2516}2517}25182519/**2520* Returns a synchronized (thread-safe) map backed by the specified2521* map. In order to guarantee serial access, it is critical that2522* <strong>all</strong> access to the backing map is accomplished2523* through the returned map.<p>2524*2525* It is imperative that the user manually synchronize on the returned2526* map when iterating over any of its collection views:2527* <pre>2528* Map m = Collections.synchronizedMap(new HashMap());2529* ...2530* Set s = m.keySet(); // Needn't be in synchronized block2531* ...2532* synchronized (m) { // Synchronizing on m, not s!2533* Iterator i = s.iterator(); // Must be in synchronized block2534* while (i.hasNext())2535* foo(i.next());2536* }2537* </pre>2538* Failure to follow this advice may result in non-deterministic behavior.2539*2540* <p>The returned map will be serializable if the specified map is2541* serializable.2542*2543* @param <K> the class of the map keys2544* @param <V> the class of the map values2545* @param m the map to be "wrapped" in a synchronized map.2546* @return a synchronized view of the specified map.2547*/2548public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {2549return new SynchronizedMap<>(m);2550}25512552/**2553* @serial include2554*/2555private static class SynchronizedMap<K,V>2556implements Map<K,V>, Serializable {2557private static final long serialVersionUID = 1978198479659022715L;25582559private final Map<K,V> m; // Backing Map2560final Object mutex; // Object on which to synchronize25612562SynchronizedMap(Map<K,V> m) {2563this.m = Objects.requireNonNull(m);2564mutex = this;2565}25662567SynchronizedMap(Map<K,V> m, Object mutex) {2568this.m = m;2569this.mutex = mutex;2570}25712572public int size() {2573synchronized (mutex) {return m.size();}2574}2575public boolean isEmpty() {2576synchronized (mutex) {return m.isEmpty();}2577}2578public boolean containsKey(Object key) {2579synchronized (mutex) {return m.containsKey(key);}2580}2581public boolean containsValue(Object value) {2582synchronized (mutex) {return m.containsValue(value);}2583}2584public V get(Object key) {2585synchronized (mutex) {return m.get(key);}2586}25872588public V put(K key, V value) {2589synchronized (mutex) {return m.put(key, value);}2590}2591public V remove(Object key) {2592synchronized (mutex) {return m.remove(key);}2593}2594public void putAll(Map<? extends K, ? extends V> map) {2595synchronized (mutex) {m.putAll(map);}2596}2597public void clear() {2598synchronized (mutex) {m.clear();}2599}26002601private transient Set<K> keySet;2602private transient Set<Map.Entry<K,V>> entrySet;2603private transient Collection<V> values;26042605public Set<K> keySet() {2606synchronized (mutex) {2607if (keySet==null)2608keySet = new SynchronizedSet<>(m.keySet(), mutex);2609return keySet;2610}2611}26122613public Set<Map.Entry<K,V>> entrySet() {2614synchronized (mutex) {2615if (entrySet==null)2616entrySet = new SynchronizedSet<>(m.entrySet(), mutex);2617return entrySet;2618}2619}26202621public Collection<V> values() {2622synchronized (mutex) {2623if (values==null)2624values = new SynchronizedCollection<>(m.values(), mutex);2625return values;2626}2627}26282629public boolean equals(Object o) {2630if (this == o)2631return true;2632synchronized (mutex) {return m.equals(o);}2633}2634public int hashCode() {2635synchronized (mutex) {return m.hashCode();}2636}2637public String toString() {2638synchronized (mutex) {return m.toString();}2639}26402641// Override default methods in Map2642@Override2643public V getOrDefault(Object k, V defaultValue) {2644synchronized (mutex) {return m.getOrDefault(k, defaultValue);}2645}2646@Override2647public void forEach(BiConsumer<? super K, ? super V> action) {2648synchronized (mutex) {m.forEach(action);}2649}2650@Override2651public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {2652synchronized (mutex) {m.replaceAll(function);}2653}2654@Override2655public V putIfAbsent(K key, V value) {2656synchronized (mutex) {return m.putIfAbsent(key, value);}2657}2658@Override2659public boolean remove(Object key, Object value) {2660synchronized (mutex) {return m.remove(key, value);}2661}2662@Override2663public boolean replace(K key, V oldValue, V newValue) {2664synchronized (mutex) {return m.replace(key, oldValue, newValue);}2665}2666@Override2667public V replace(K key, V value) {2668synchronized (mutex) {return m.replace(key, value);}2669}2670@Override2671public V computeIfAbsent(K key,2672Function<? super K, ? extends V> mappingFunction) {2673synchronized (mutex) {return m.computeIfAbsent(key, mappingFunction);}2674}2675@Override2676public V computeIfPresent(K key,2677BiFunction<? super K, ? super V, ? extends V> remappingFunction) {2678synchronized (mutex) {return m.computeIfPresent(key, remappingFunction);}2679}2680@Override2681public V compute(K key,2682BiFunction<? super K, ? super V, ? extends V> remappingFunction) {2683synchronized (mutex) {return m.compute(key, remappingFunction);}2684}2685@Override2686public V merge(K key, V value,2687BiFunction<? super V, ? super V, ? extends V> remappingFunction) {2688synchronized (mutex) {return m.merge(key, value, remappingFunction);}2689}26902691private void writeObject(ObjectOutputStream s) throws IOException {2692synchronized (mutex) {s.defaultWriteObject();}2693}2694}26952696/**2697* Returns a synchronized (thread-safe) sorted map backed by the specified2698* sorted map. In order to guarantee serial access, it is critical that2699* <strong>all</strong> access to the backing sorted map is accomplished2700* through the returned sorted map (or its views).<p>2701*2702* It is imperative that the user manually synchronize on the returned2703* sorted map when iterating over any of its collection views, or the2704* collections views of any of its <tt>subMap</tt>, <tt>headMap</tt> or2705* <tt>tailMap</tt> views.2706* <pre>2707* SortedMap m = Collections.synchronizedSortedMap(new TreeMap());2708* ...2709* Set s = m.keySet(); // Needn't be in synchronized block2710* ...2711* synchronized (m) { // Synchronizing on m, not s!2712* Iterator i = s.iterator(); // Must be in synchronized block2713* while (i.hasNext())2714* foo(i.next());2715* }2716* </pre>2717* or:2718* <pre>2719* SortedMap m = Collections.synchronizedSortedMap(new TreeMap());2720* SortedMap m2 = m.subMap(foo, bar);2721* ...2722* Set s2 = m2.keySet(); // Needn't be in synchronized block2723* ...2724* synchronized (m) { // Synchronizing on m, not m2 or s2!2725* Iterator i = s.iterator(); // Must be in synchronized block2726* while (i.hasNext())2727* foo(i.next());2728* }2729* </pre>2730* Failure to follow this advice may result in non-deterministic behavior.2731*2732* <p>The returned sorted map will be serializable if the specified2733* sorted map is serializable.2734*2735* @param <K> the class of the map keys2736* @param <V> the class of the map values2737* @param m the sorted map to be "wrapped" in a synchronized sorted map.2738* @return a synchronized view of the specified sorted map.2739*/2740public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {2741return new SynchronizedSortedMap<>(m);2742}27432744/**2745* @serial include2746*/2747static class SynchronizedSortedMap<K,V>2748extends SynchronizedMap<K,V>2749implements SortedMap<K,V>2750{2751private static final long serialVersionUID = -8798146769416483793L;27522753private final SortedMap<K,V> sm;27542755SynchronizedSortedMap(SortedMap<K,V> m) {2756super(m);2757sm = m;2758}2759SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {2760super(m, mutex);2761sm = m;2762}27632764public Comparator<? super K> comparator() {2765synchronized (mutex) {return sm.comparator();}2766}27672768public SortedMap<K,V> subMap(K fromKey, K toKey) {2769synchronized (mutex) {2770return new SynchronizedSortedMap<>(2771sm.subMap(fromKey, toKey), mutex);2772}2773}2774public SortedMap<K,V> headMap(K toKey) {2775synchronized (mutex) {2776return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);2777}2778}2779public SortedMap<K,V> tailMap(K fromKey) {2780synchronized (mutex) {2781return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);2782}2783}27842785public K firstKey() {2786synchronized (mutex) {return sm.firstKey();}2787}2788public K lastKey() {2789synchronized (mutex) {return sm.lastKey();}2790}2791}27922793/**2794* Returns a synchronized (thread-safe) navigable map backed by the2795* specified navigable map. In order to guarantee serial access, it is2796* critical that <strong>all</strong> access to the backing navigable map is2797* accomplished through the returned navigable map (or its views).<p>2798*2799* It is imperative that the user manually synchronize on the returned2800* navigable map when iterating over any of its collection views, or the2801* collections views of any of its {@code subMap}, {@code headMap} or2802* {@code tailMap} views.2803* <pre>2804* NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());2805* ...2806* Set s = m.keySet(); // Needn't be in synchronized block2807* ...2808* synchronized (m) { // Synchronizing on m, not s!2809* Iterator i = s.iterator(); // Must be in synchronized block2810* while (i.hasNext())2811* foo(i.next());2812* }2813* </pre>2814* or:2815* <pre>2816* NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());2817* NavigableMap m2 = m.subMap(foo, true, bar, false);2818* ...2819* Set s2 = m2.keySet(); // Needn't be in synchronized block2820* ...2821* synchronized (m) { // Synchronizing on m, not m2 or s2!2822* Iterator i = s.iterator(); // Must be in synchronized block2823* while (i.hasNext())2824* foo(i.next());2825* }2826* </pre>2827* Failure to follow this advice may result in non-deterministic behavior.2828*2829* <p>The returned navigable map will be serializable if the specified2830* navigable map is serializable.2831*2832* @param <K> the class of the map keys2833* @param <V> the class of the map values2834* @param m the navigable map to be "wrapped" in a synchronized navigable2835* map2836* @return a synchronized view of the specified navigable map.2837* @since 1.82838*/2839public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) {2840return new SynchronizedNavigableMap<>(m);2841}28422843/**2844* A synchronized NavigableMap.2845*2846* @serial include2847*/2848static class SynchronizedNavigableMap<K,V>2849extends SynchronizedSortedMap<K,V>2850implements NavigableMap<K,V>2851{2852private static final long serialVersionUID = 699392247599746807L;28532854private final NavigableMap<K,V> nm;28552856SynchronizedNavigableMap(NavigableMap<K,V> m) {2857super(m);2858nm = m;2859}2860SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) {2861super(m, mutex);2862nm = m;2863}28642865public Entry<K, V> lowerEntry(K key)2866{ synchronized (mutex) { return nm.lowerEntry(key); } }2867public K lowerKey(K key)2868{ synchronized (mutex) { return nm.lowerKey(key); } }2869public Entry<K, V> floorEntry(K key)2870{ synchronized (mutex) { return nm.floorEntry(key); } }2871public K floorKey(K key)2872{ synchronized (mutex) { return nm.floorKey(key); } }2873public Entry<K, V> ceilingEntry(K key)2874{ synchronized (mutex) { return nm.ceilingEntry(key); } }2875public K ceilingKey(K key)2876{ synchronized (mutex) { return nm.ceilingKey(key); } }2877public Entry<K, V> higherEntry(K key)2878{ synchronized (mutex) { return nm.higherEntry(key); } }2879public K higherKey(K key)2880{ synchronized (mutex) { return nm.higherKey(key); } }2881public Entry<K, V> firstEntry()2882{ synchronized (mutex) { return nm.firstEntry(); } }2883public Entry<K, V> lastEntry()2884{ synchronized (mutex) { return nm.lastEntry(); } }2885public Entry<K, V> pollFirstEntry()2886{ synchronized (mutex) { return nm.pollFirstEntry(); } }2887public Entry<K, V> pollLastEntry()2888{ synchronized (mutex) { return nm.pollLastEntry(); } }28892890public NavigableMap<K, V> descendingMap() {2891synchronized (mutex) {2892return2893new SynchronizedNavigableMap<>(nm.descendingMap(), mutex);2894}2895}28962897public NavigableSet<K> keySet() {2898return navigableKeySet();2899}29002901public NavigableSet<K> navigableKeySet() {2902synchronized (mutex) {2903return new SynchronizedNavigableSet<>(nm.navigableKeySet(), mutex);2904}2905}29062907public NavigableSet<K> descendingKeySet() {2908synchronized (mutex) {2909return new SynchronizedNavigableSet<>(nm.descendingKeySet(), mutex);2910}2911}291229132914public SortedMap<K,V> subMap(K fromKey, K toKey) {2915synchronized (mutex) {2916return new SynchronizedNavigableMap<>(2917nm.subMap(fromKey, true, toKey, false), mutex);2918}2919}2920public SortedMap<K,V> headMap(K toKey) {2921synchronized (mutex) {2922return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex);2923}2924}2925public SortedMap<K,V> tailMap(K fromKey) {2926synchronized (mutex) {2927return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex);2928}2929}29302931public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {2932synchronized (mutex) {2933return new SynchronizedNavigableMap<>(2934nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex);2935}2936}29372938public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {2939synchronized (mutex) {2940return new SynchronizedNavigableMap<>(2941nm.headMap(toKey, inclusive), mutex);2942}2943}29442945public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {2946synchronized (mutex) {2947return new SynchronizedNavigableMap<>(2948nm.tailMap(fromKey, inclusive), mutex);2949}2950}2951}29522953// Dynamically typesafe collection wrappers29542955/**2956* Returns a dynamically typesafe view of the specified collection.2957* Any attempt to insert an element of the wrong type will result in an2958* immediate {@link ClassCastException}. Assuming a collection2959* contains no incorrectly typed elements prior to the time a2960* dynamically typesafe view is generated, and that all subsequent2961* access to the collection takes place through the view, it is2962* <i>guaranteed</i> that the collection cannot contain an incorrectly2963* typed element.2964*2965* <p>The generics mechanism in the language provides compile-time2966* (static) type checking, but it is possible to defeat this mechanism2967* with unchecked casts. Usually this is not a problem, as the compiler2968* issues warnings on all such unchecked operations. There are, however,2969* times when static type checking alone is not sufficient. For example,2970* suppose a collection is passed to a third-party library and it is2971* imperative that the library code not corrupt the collection by2972* inserting an element of the wrong type.2973*2974* <p>Another use of dynamically typesafe views is debugging. Suppose a2975* program fails with a {@code ClassCastException}, indicating that an2976* incorrectly typed element was put into a parameterized collection.2977* Unfortunately, the exception can occur at any time after the erroneous2978* element is inserted, so it typically provides little or no information2979* as to the real source of the problem. If the problem is reproducible,2980* one can quickly determine its source by temporarily modifying the2981* program to wrap the collection with a dynamically typesafe view.2982* For example, this declaration:2983* <pre> {@code2984* Collection<String> c = new HashSet<>();2985* }</pre>2986* may be replaced temporarily by this one:2987* <pre> {@code2988* Collection<String> c = Collections.checkedCollection(2989* new HashSet<>(), String.class);2990* }</pre>2991* Running the program again will cause it to fail at the point where2992* an incorrectly typed element is inserted into the collection, clearly2993* identifying the source of the problem. Once the problem is fixed, the2994* modified declaration may be reverted back to the original.2995*2996* <p>The returned collection does <i>not</i> pass the hashCode and equals2997* operations through to the backing collection, but relies on2998* {@code Object}'s {@code equals} and {@code hashCode} methods. This2999* is necessary to preserve the contracts of these operations in the case3000* that the backing collection is a set or a list.3001*3002* <p>The returned collection will be serializable if the specified3003* collection is serializable.3004*3005* <p>Since {@code null} is considered to be a value of any reference3006* type, the returned collection permits insertion of null elements3007* whenever the backing collection does.3008*3009* @param <E> the class of the objects in the collection3010* @param c the collection for which a dynamically typesafe view is to be3011* returned3012* @param type the type of element that {@code c} is permitted to hold3013* @return a dynamically typesafe view of the specified collection3014* @since 1.53015*/3016public static <E> Collection<E> checkedCollection(Collection<E> c,3017Class<E> type) {3018return new CheckedCollection<>(c, type);3019}30203021@SuppressWarnings("unchecked")3022static <T> T[] zeroLengthArray(Class<T> type) {3023return (T[]) Array.newInstance(type, 0);3024}30253026/**3027* @serial include3028*/3029static class CheckedCollection<E> implements Collection<E>, Serializable {3030private static final long serialVersionUID = 1578914078182001775L;30313032final Collection<E> c;3033final Class<E> type;30343035@SuppressWarnings("unchecked")3036E typeCheck(Object o) {3037if (o != null && !type.isInstance(o))3038throw new ClassCastException(badElementMsg(o));3039return (E) o;3040}30413042private String badElementMsg(Object o) {3043return "Attempt to insert " + o.getClass() +3044" element into collection with element type " + type;3045}30463047CheckedCollection(Collection<E> c, Class<E> type) {3048this.c = Objects.requireNonNull(c, "c");3049this.type = Objects.requireNonNull(type, "type");3050}30513052public int size() { return c.size(); }3053public boolean isEmpty() { return c.isEmpty(); }3054public boolean contains(Object o) { return c.contains(o); }3055public Object[] toArray() { return c.toArray(); }3056public <T> T[] toArray(T[] a) { return c.toArray(a); }3057public String toString() { return c.toString(); }3058public boolean remove(Object o) { return c.remove(o); }3059public void clear() { c.clear(); }30603061public boolean containsAll(Collection<?> coll) {3062return c.containsAll(coll);3063}3064public boolean removeAll(Collection<?> coll) {3065return c.removeAll(coll);3066}3067public boolean retainAll(Collection<?> coll) {3068return c.retainAll(coll);3069}30703071public Iterator<E> iterator() {3072// JDK-6363904 - unwrapped iterator could be typecast to3073// ListIterator with unsafe set()3074final Iterator<E> it = c.iterator();3075return new Iterator<E>() {3076public boolean hasNext() { return it.hasNext(); }3077public E next() { return it.next(); }3078public void remove() { it.remove(); }};3079}30803081public boolean add(E e) { return c.add(typeCheck(e)); }30823083private E[] zeroLengthElementArray; // Lazily initialized30843085private E[] zeroLengthElementArray() {3086return zeroLengthElementArray != null ? zeroLengthElementArray :3087(zeroLengthElementArray = zeroLengthArray(type));3088}30893090@SuppressWarnings("unchecked")3091Collection<E> checkedCopyOf(Collection<? extends E> coll) {3092Object[] a;3093try {3094E[] z = zeroLengthElementArray();3095a = coll.toArray(z);3096// Defend against coll violating the toArray contract3097if (a.getClass() != z.getClass())3098a = Arrays.copyOf(a, a.length, z.getClass());3099} catch (ArrayStoreException ignore) {3100// To get better and consistent diagnostics,3101// we call typeCheck explicitly on each element.3102// We call clone() to defend against coll retaining a3103// reference to the returned array and storing a bad3104// element into it after it has been type checked.3105a = coll.toArray().clone();3106for (Object o : a)3107typeCheck(o);3108}3109// A slight abuse of the type system, but safe here.3110return (Collection<E>) Arrays.asList(a);3111}31123113public boolean addAll(Collection<? extends E> coll) {3114// Doing things this way insulates us from concurrent changes3115// in the contents of coll and provides all-or-nothing3116// semantics (which we wouldn't get if we type-checked each3117// element as we added it)3118return c.addAll(checkedCopyOf(coll));3119}31203121// Override default methods in Collection3122@Override3123public void forEach(Consumer<? super E> action) {c.forEach(action);}3124@Override3125public boolean removeIf(Predicate<? super E> filter) {3126return c.removeIf(filter);3127}3128@Override3129public Spliterator<E> spliterator() {return c.spliterator();}3130@Override3131public Stream<E> stream() {return c.stream();}3132@Override3133public Stream<E> parallelStream() {return c.parallelStream();}3134}31353136/**3137* Returns a dynamically typesafe view of the specified queue.3138* Any attempt to insert an element of the wrong type will result in3139* an immediate {@link ClassCastException}. Assuming a queue contains3140* no incorrectly typed elements prior to the time a dynamically typesafe3141* view is generated, and that all subsequent access to the queue3142* takes place through the view, it is <i>guaranteed</i> that the3143* queue cannot contain an incorrectly typed element.3144*3145* <p>A discussion of the use of dynamically typesafe views may be3146* found in the documentation for the {@link #checkedCollection3147* checkedCollection} method.3148*3149* <p>The returned queue will be serializable if the specified queue3150* is serializable.3151*3152* <p>Since {@code null} is considered to be a value of any reference3153* type, the returned queue permits insertion of {@code null} elements3154* whenever the backing queue does.3155*3156* @param <E> the class of the objects in the queue3157* @param queue the queue for which a dynamically typesafe view is to be3158* returned3159* @param type the type of element that {@code queue} is permitted to hold3160* @return a dynamically typesafe view of the specified queue3161* @since 1.83162*/3163public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type) {3164return new CheckedQueue<>(queue, type);3165}31663167/**3168* @serial include3169*/3170static class CheckedQueue<E>3171extends CheckedCollection<E>3172implements Queue<E>, Serializable3173{3174private static final long serialVersionUID = 1433151992604707767L;3175final Queue<E> queue;31763177CheckedQueue(Queue<E> queue, Class<E> elementType) {3178super(queue, elementType);3179this.queue = queue;3180}31813182public E element() {return queue.element();}3183public boolean equals(Object o) {return o == this || c.equals(o);}3184public int hashCode() {return c.hashCode();}3185public E peek() {return queue.peek();}3186public E poll() {return queue.poll();}3187public E remove() {return queue.remove();}3188public boolean offer(E e) {return queue.offer(typeCheck(e));}3189}31903191/**3192* Returns a dynamically typesafe view of the specified set.3193* Any attempt to insert an element of the wrong type will result in3194* an immediate {@link ClassCastException}. Assuming a set contains3195* no incorrectly typed elements prior to the time a dynamically typesafe3196* view is generated, and that all subsequent access to the set3197* takes place through the view, it is <i>guaranteed</i> that the3198* set cannot contain an incorrectly typed element.3199*3200* <p>A discussion of the use of dynamically typesafe views may be3201* found in the documentation for the {@link #checkedCollection3202* checkedCollection} method.3203*3204* <p>The returned set will be serializable if the specified set is3205* serializable.3206*3207* <p>Since {@code null} is considered to be a value of any reference3208* type, the returned set permits insertion of null elements whenever3209* the backing set does.3210*3211* @param <E> the class of the objects in the set3212* @param s the set for which a dynamically typesafe view is to be3213* returned3214* @param type the type of element that {@code s} is permitted to hold3215* @return a dynamically typesafe view of the specified set3216* @since 1.53217*/3218public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {3219return new CheckedSet<>(s, type);3220}32213222/**3223* @serial include3224*/3225static class CheckedSet<E> extends CheckedCollection<E>3226implements Set<E>, Serializable3227{3228private static final long serialVersionUID = 4694047833775013803L;32293230CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }32313232public boolean equals(Object o) { return o == this || c.equals(o); }3233public int hashCode() { return c.hashCode(); }3234}32353236/**3237* Returns a dynamically typesafe view of the specified sorted set.3238* Any attempt to insert an element of the wrong type will result in an3239* immediate {@link ClassCastException}. Assuming a sorted set3240* contains no incorrectly typed elements prior to the time a3241* dynamically typesafe view is generated, and that all subsequent3242* access to the sorted set takes place through the view, it is3243* <i>guaranteed</i> that the sorted set cannot contain an incorrectly3244* typed element.3245*3246* <p>A discussion of the use of dynamically typesafe views may be3247* found in the documentation for the {@link #checkedCollection3248* checkedCollection} method.3249*3250* <p>The returned sorted set will be serializable if the specified sorted3251* set is serializable.3252*3253* <p>Since {@code null} is considered to be a value of any reference3254* type, the returned sorted set permits insertion of null elements3255* whenever the backing sorted set does.3256*3257* @param <E> the class of the objects in the set3258* @param s the sorted set for which a dynamically typesafe view is to be3259* returned3260* @param type the type of element that {@code s} is permitted to hold3261* @return a dynamically typesafe view of the specified sorted set3262* @since 1.53263*/3264public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,3265Class<E> type) {3266return new CheckedSortedSet<>(s, type);3267}32683269/**3270* @serial include3271*/3272static class CheckedSortedSet<E> extends CheckedSet<E>3273implements SortedSet<E>, Serializable3274{3275private static final long serialVersionUID = 1599911165492914959L;32763277private final SortedSet<E> ss;32783279CheckedSortedSet(SortedSet<E> s, Class<E> type) {3280super(s, type);3281ss = s;3282}32833284public Comparator<? super E> comparator() { return ss.comparator(); }3285public E first() { return ss.first(); }3286public E last() { return ss.last(); }32873288public SortedSet<E> subSet(E fromElement, E toElement) {3289return checkedSortedSet(ss.subSet(fromElement,toElement), type);3290}3291public SortedSet<E> headSet(E toElement) {3292return checkedSortedSet(ss.headSet(toElement), type);3293}3294public SortedSet<E> tailSet(E fromElement) {3295return checkedSortedSet(ss.tailSet(fromElement), type);3296}3297}32983299/**3300* Returns a dynamically typesafe view of the specified navigable set.3301* Any attempt to insert an element of the wrong type will result in an3302* immediate {@link ClassCastException}. Assuming a navigable set3303* contains no incorrectly typed elements prior to the time a3304* dynamically typesafe view is generated, and that all subsequent3305* access to the navigable set takes place through the view, it is3306* <em>guaranteed</em> that the navigable set cannot contain an incorrectly3307* typed element.3308*3309* <p>A discussion of the use of dynamically typesafe views may be3310* found in the documentation for the {@link #checkedCollection3311* checkedCollection} method.3312*3313* <p>The returned navigable set will be serializable if the specified3314* navigable set is serializable.3315*3316* <p>Since {@code null} is considered to be a value of any reference3317* type, the returned navigable set permits insertion of null elements3318* whenever the backing sorted set does.3319*3320* @param <E> the class of the objects in the set3321* @param s the navigable set for which a dynamically typesafe view is to be3322* returned3323* @param type the type of element that {@code s} is permitted to hold3324* @return a dynamically typesafe view of the specified navigable set3325* @since 1.83326*/3327public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,3328Class<E> type) {3329return new CheckedNavigableSet<>(s, type);3330}33313332/**3333* @serial include3334*/3335static class CheckedNavigableSet<E> extends CheckedSortedSet<E>3336implements NavigableSet<E>, Serializable3337{3338private static final long serialVersionUID = -5429120189805438922L;33393340private final NavigableSet<E> ns;33413342CheckedNavigableSet(NavigableSet<E> s, Class<E> type) {3343super(s, type);3344ns = s;3345}33463347public E lower(E e) { return ns.lower(e); }3348public E floor(E e) { return ns.floor(e); }3349public E ceiling(E e) { return ns.ceiling(e); }3350public E higher(E e) { return ns.higher(e); }3351public E pollFirst() { return ns.pollFirst(); }3352public E pollLast() {return ns.pollLast(); }3353public NavigableSet<E> descendingSet()3354{ return checkedNavigableSet(ns.descendingSet(), type); }3355public Iterator<E> descendingIterator()3356{return checkedNavigableSet(ns.descendingSet(), type).iterator(); }33573358public NavigableSet<E> subSet(E fromElement, E toElement) {3359return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type);3360}3361public NavigableSet<E> headSet(E toElement) {3362return checkedNavigableSet(ns.headSet(toElement, false), type);3363}3364public NavigableSet<E> tailSet(E fromElement) {3365return checkedNavigableSet(ns.tailSet(fromElement, true), type);3366}33673368public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {3369return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type);3370}33713372public NavigableSet<E> headSet(E toElement, boolean inclusive) {3373return checkedNavigableSet(ns.headSet(toElement, inclusive), type);3374}33753376public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {3377return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type);3378}3379}33803381/**3382* Returns a dynamically typesafe view of the specified list.3383* Any attempt to insert an element of the wrong type will result in3384* an immediate {@link ClassCastException}. Assuming a list contains3385* no incorrectly typed elements prior to the time a dynamically typesafe3386* view is generated, and that all subsequent access to the list3387* takes place through the view, it is <i>guaranteed</i> that the3388* list cannot contain an incorrectly typed element.3389*3390* <p>A discussion of the use of dynamically typesafe views may be3391* found in the documentation for the {@link #checkedCollection3392* checkedCollection} method.3393*3394* <p>The returned list will be serializable if the specified list3395* is serializable.3396*3397* <p>Since {@code null} is considered to be a value of any reference3398* type, the returned list permits insertion of null elements whenever3399* the backing list does.3400*3401* @param <E> the class of the objects in the list3402* @param list the list for which a dynamically typesafe view is to be3403* returned3404* @param type the type of element that {@code list} is permitted to hold3405* @return a dynamically typesafe view of the specified list3406* @since 1.53407*/3408public static <E> List<E> checkedList(List<E> list, Class<E> type) {3409return (list instanceof RandomAccess ?3410new CheckedRandomAccessList<>(list, type) :3411new CheckedList<>(list, type));3412}34133414/**3415* @serial include3416*/3417static class CheckedList<E>3418extends CheckedCollection<E>3419implements List<E>3420{3421private static final long serialVersionUID = 65247728283967356L;3422final List<E> list;34233424CheckedList(List<E> list, Class<E> type) {3425super(list, type);3426this.list = list;3427}34283429public boolean equals(Object o) { return o == this || list.equals(o); }3430public int hashCode() { return list.hashCode(); }3431public E get(int index) { return list.get(index); }3432public E remove(int index) { return list.remove(index); }3433public int indexOf(Object o) { return list.indexOf(o); }3434public int lastIndexOf(Object o) { return list.lastIndexOf(o); }34353436public E set(int index, E element) {3437return list.set(index, typeCheck(element));3438}34393440public void add(int index, E element) {3441list.add(index, typeCheck(element));3442}34433444public boolean addAll(int index, Collection<? extends E> c) {3445return list.addAll(index, checkedCopyOf(c));3446}3447public ListIterator<E> listIterator() { return listIterator(0); }34483449public ListIterator<E> listIterator(final int index) {3450final ListIterator<E> i = list.listIterator(index);34513452return new ListIterator<E>() {3453public boolean hasNext() { return i.hasNext(); }3454public E next() { return i.next(); }3455public boolean hasPrevious() { return i.hasPrevious(); }3456public E previous() { return i.previous(); }3457public int nextIndex() { return i.nextIndex(); }3458public int previousIndex() { return i.previousIndex(); }3459public void remove() { i.remove(); }34603461public void set(E e) {3462i.set(typeCheck(e));3463}34643465public void add(E e) {3466i.add(typeCheck(e));3467}34683469@Override3470public void forEachRemaining(Consumer<? super E> action) {3471i.forEachRemaining(action);3472}3473};3474}34753476public List<E> subList(int fromIndex, int toIndex) {3477return new CheckedList<>(list.subList(fromIndex, toIndex), type);3478}34793480/**3481* {@inheritDoc}3482*3483* @throws ClassCastException if the class of an element returned by the3484* operator prevents it from being added to this collection. The3485* exception may be thrown after some elements of the list have3486* already been replaced.3487*/3488@Override3489public void replaceAll(UnaryOperator<E> operator) {3490Objects.requireNonNull(operator);3491list.replaceAll(e -> typeCheck(operator.apply(e)));3492}34933494@Override3495public void sort(Comparator<? super E> c) {3496list.sort(c);3497}3498}34993500/**3501* @serial include3502*/3503static class CheckedRandomAccessList<E> extends CheckedList<E>3504implements RandomAccess3505{3506private static final long serialVersionUID = 1638200125423088369L;35073508CheckedRandomAccessList(List<E> list, Class<E> type) {3509super(list, type);3510}35113512public List<E> subList(int fromIndex, int toIndex) {3513return new CheckedRandomAccessList<>(3514list.subList(fromIndex, toIndex), type);3515}3516}35173518/**3519* Returns a dynamically typesafe view of the specified map.3520* Any attempt to insert a mapping whose key or value have the wrong3521* type will result in an immediate {@link ClassCastException}.3522* Similarly, any attempt to modify the value currently associated with3523* a key will result in an immediate {@link ClassCastException},3524* whether the modification is attempted directly through the map3525* itself, or through a {@link Map.Entry} instance obtained from the3526* map's {@link Map#entrySet() entry set} view.3527*3528* <p>Assuming a map contains no incorrectly typed keys or values3529* prior to the time a dynamically typesafe view is generated, and3530* that all subsequent access to the map takes place through the view3531* (or one of its collection views), it is <i>guaranteed</i> that the3532* map cannot contain an incorrectly typed key or value.3533*3534* <p>A discussion of the use of dynamically typesafe views may be3535* found in the documentation for the {@link #checkedCollection3536* checkedCollection} method.3537*3538* <p>The returned map will be serializable if the specified map is3539* serializable.3540*3541* <p>Since {@code null} is considered to be a value of any reference3542* type, the returned map permits insertion of null keys or values3543* whenever the backing map does.3544*3545* @param <K> the class of the map keys3546* @param <V> the class of the map values3547* @param m the map for which a dynamically typesafe view is to be3548* returned3549* @param keyType the type of key that {@code m} is permitted to hold3550* @param valueType the type of value that {@code m} is permitted to hold3551* @return a dynamically typesafe view of the specified map3552* @since 1.53553*/3554public static <K, V> Map<K, V> checkedMap(Map<K, V> m,3555Class<K> keyType,3556Class<V> valueType) {3557return new CheckedMap<>(m, keyType, valueType);3558}355935603561/**3562* @serial include3563*/3564private static class CheckedMap<K,V>3565implements Map<K,V>, Serializable3566{3567private static final long serialVersionUID = 5742860141034234728L;35683569private final Map<K, V> m;3570final Class<K> keyType;3571final Class<V> valueType;35723573private void typeCheck(Object key, Object value) {3574if (key != null && !keyType.isInstance(key))3575throw new ClassCastException(badKeyMsg(key));35763577if (value != null && !valueType.isInstance(value))3578throw new ClassCastException(badValueMsg(value));3579}35803581private BiFunction<? super K, ? super V, ? extends V> typeCheck(3582BiFunction<? super K, ? super V, ? extends V> func) {3583Objects.requireNonNull(func);3584return (k, v) -> {3585V newValue = func.apply(k, v);3586typeCheck(k, newValue);3587return newValue;3588};3589}35903591private String badKeyMsg(Object key) {3592return "Attempt to insert " + key.getClass() +3593" key into map with key type " + keyType;3594}35953596private String badValueMsg(Object value) {3597return "Attempt to insert " + value.getClass() +3598" value into map with value type " + valueType;3599}36003601CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {3602this.m = Objects.requireNonNull(m);3603this.keyType = Objects.requireNonNull(keyType);3604this.valueType = Objects.requireNonNull(valueType);3605}36063607public int size() { return m.size(); }3608public boolean isEmpty() { return m.isEmpty(); }3609public boolean containsKey(Object key) { return m.containsKey(key); }3610public boolean containsValue(Object v) { return m.containsValue(v); }3611public V get(Object key) { return m.get(key); }3612public V remove(Object key) { return m.remove(key); }3613public void clear() { m.clear(); }3614public Set<K> keySet() { return m.keySet(); }3615public Collection<V> values() { return m.values(); }3616public boolean equals(Object o) { return o == this || m.equals(o); }3617public int hashCode() { return m.hashCode(); }3618public String toString() { return m.toString(); }36193620public V put(K key, V value) {3621typeCheck(key, value);3622return m.put(key, value);3623}36243625@SuppressWarnings("unchecked")3626public void putAll(Map<? extends K, ? extends V> t) {3627// Satisfy the following goals:3628// - good diagnostics in case of type mismatch3629// - all-or-nothing semantics3630// - protection from malicious t3631// - correct behavior if t is a concurrent map3632Object[] entries = t.entrySet().toArray();3633List<Map.Entry<K,V>> checked = new ArrayList<>(entries.length);3634for (Object o : entries) {3635Map.Entry<?,?> e = (Map.Entry<?,?>) o;3636Object k = e.getKey();3637Object v = e.getValue();3638typeCheck(k, v);3639checked.add(3640new AbstractMap.SimpleImmutableEntry<>((K)k, (V)v));3641}3642for (Map.Entry<K,V> e : checked)3643m.put(e.getKey(), e.getValue());3644}36453646private transient Set<Map.Entry<K,V>> entrySet;36473648public Set<Map.Entry<K,V>> entrySet() {3649if (entrySet==null)3650entrySet = new CheckedEntrySet<>(m.entrySet(), valueType);3651return entrySet;3652}36533654// Override default methods in Map3655@Override3656public void forEach(BiConsumer<? super K, ? super V> action) {3657m.forEach(action);3658}36593660@Override3661public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {3662m.replaceAll(typeCheck(function));3663}36643665@Override3666public V putIfAbsent(K key, V value) {3667typeCheck(key, value);3668return m.putIfAbsent(key, value);3669}36703671@Override3672public boolean remove(Object key, Object value) {3673return m.remove(key, value);3674}36753676@Override3677public boolean replace(K key, V oldValue, V newValue) {3678typeCheck(key, newValue);3679return m.replace(key, oldValue, newValue);3680}36813682@Override3683public V replace(K key, V value) {3684typeCheck(key, value);3685return m.replace(key, value);3686}36873688@Override3689public V computeIfAbsent(K key,3690Function<? super K, ? extends V> mappingFunction) {3691Objects.requireNonNull(mappingFunction);3692return m.computeIfAbsent(key, k -> {3693V value = mappingFunction.apply(k);3694typeCheck(k, value);3695return value;3696});3697}36983699@Override3700public V computeIfPresent(K key,3701BiFunction<? super K, ? super V, ? extends V> remappingFunction) {3702return m.computeIfPresent(key, typeCheck(remappingFunction));3703}37043705@Override3706public V compute(K key,3707BiFunction<? super K, ? super V, ? extends V> remappingFunction) {3708return m.compute(key, typeCheck(remappingFunction));3709}37103711@Override3712public V merge(K key, V value,3713BiFunction<? super V, ? super V, ? extends V> remappingFunction) {3714Objects.requireNonNull(remappingFunction);3715return m.merge(key, value, (v1, v2) -> {3716V newValue = remappingFunction.apply(v1, v2);3717typeCheck(null, newValue);3718return newValue;3719});3720}37213722/**3723* We need this class in addition to CheckedSet as Map.Entry permits3724* modification of the backing Map via the setValue operation. This3725* class is subtle: there are many possible attacks that must be3726* thwarted.3727*3728* @serial exclude3729*/3730static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {3731private final Set<Map.Entry<K,V>> s;3732private final Class<V> valueType;37333734CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {3735this.s = s;3736this.valueType = valueType;3737}37383739public int size() { return s.size(); }3740public boolean isEmpty() { return s.isEmpty(); }3741public String toString() { return s.toString(); }3742public int hashCode() { return s.hashCode(); }3743public void clear() { s.clear(); }37443745public boolean add(Map.Entry<K, V> e) {3746throw new UnsupportedOperationException();3747}3748public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {3749throw new UnsupportedOperationException();3750}37513752public Iterator<Map.Entry<K,V>> iterator() {3753final Iterator<Map.Entry<K, V>> i = s.iterator();3754final Class<V> valueType = this.valueType;37553756return new Iterator<Map.Entry<K,V>>() {3757public boolean hasNext() { return i.hasNext(); }3758public void remove() { i.remove(); }37593760public Map.Entry<K,V> next() {3761return checkedEntry(i.next(), valueType);3762}3763};3764}37653766@SuppressWarnings("unchecked")3767public Object[] toArray() {3768Object[] source = s.toArray();37693770/*3771* Ensure that we don't get an ArrayStoreException even if3772* s.toArray returns an array of something other than Object3773*/3774Object[] dest = (CheckedEntry.class.isInstance(3775source.getClass().getComponentType()) ? source :3776new Object[source.length]);37773778for (int i = 0; i < source.length; i++)3779dest[i] = checkedEntry((Map.Entry<K,V>)source[i],3780valueType);3781return dest;3782}37833784@SuppressWarnings("unchecked")3785public <T> T[] toArray(T[] a) {3786// We don't pass a to s.toArray, to avoid window of3787// vulnerability wherein an unscrupulous multithreaded client3788// could get his hands on raw (unwrapped) Entries from s.3789T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));37903791for (int i=0; i<arr.length; i++)3792arr[i] = (T) checkedEntry((Map.Entry<K,V>)arr[i],3793valueType);3794if (arr.length > a.length)3795return arr;37963797System.arraycopy(arr, 0, a, 0, arr.length);3798if (a.length > arr.length)3799a[arr.length] = null;3800return a;3801}38023803/**3804* This method is overridden to protect the backing set against3805* an object with a nefarious equals function that senses3806* that the equality-candidate is Map.Entry and calls its3807* setValue method.3808*/3809public boolean contains(Object o) {3810if (!(o instanceof Map.Entry))3811return false;3812Map.Entry<?,?> e = (Map.Entry<?,?>) o;3813return s.contains(3814(e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));3815}38163817/**3818* The bulk collection methods are overridden to protect3819* against an unscrupulous collection whose contains(Object o)3820* method senses when o is a Map.Entry, and calls o.setValue.3821*/3822public boolean containsAll(Collection<?> c) {3823for (Object o : c)3824if (!contains(o)) // Invokes safe contains() above3825return false;3826return true;3827}38283829public boolean remove(Object o) {3830if (!(o instanceof Map.Entry))3831return false;3832return s.remove(new AbstractMap.SimpleImmutableEntry3833<>((Map.Entry<?,?>)o));3834}38353836public boolean removeAll(Collection<?> c) {3837return batchRemove(c, false);3838}3839public boolean retainAll(Collection<?> c) {3840return batchRemove(c, true);3841}3842private boolean batchRemove(Collection<?> c, boolean complement) {3843Objects.requireNonNull(c);3844boolean modified = false;3845Iterator<Map.Entry<K,V>> it = iterator();3846while (it.hasNext()) {3847if (c.contains(it.next()) != complement) {3848it.remove();3849modified = true;3850}3851}3852return modified;3853}38543855public boolean equals(Object o) {3856if (o == this)3857return true;3858if (!(o instanceof Set))3859return false;3860Set<?> that = (Set<?>) o;3861return that.size() == s.size()3862&& containsAll(that); // Invokes safe containsAll() above3863}38643865static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,3866Class<T> valueType) {3867return new CheckedEntry<>(e, valueType);3868}38693870/**3871* This "wrapper class" serves two purposes: it prevents3872* the client from modifying the backing Map, by short-circuiting3873* the setValue method, and it protects the backing Map against3874* an ill-behaved Map.Entry that attempts to modify another3875* Map.Entry when asked to perform an equality check.3876*/3877private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {3878private final Map.Entry<K, V> e;3879private final Class<T> valueType;38803881CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {3882this.e = Objects.requireNonNull(e);3883this.valueType = Objects.requireNonNull(valueType);3884}38853886public K getKey() { return e.getKey(); }3887public V getValue() { return e.getValue(); }3888public int hashCode() { return e.hashCode(); }3889public String toString() { return e.toString(); }38903891public V setValue(V value) {3892if (value != null && !valueType.isInstance(value))3893throw new ClassCastException(badValueMsg(value));3894return e.setValue(value);3895}38963897private String badValueMsg(Object value) {3898return "Attempt to insert " + value.getClass() +3899" value into map with value type " + valueType;3900}39013902public boolean equals(Object o) {3903if (o == this)3904return true;3905if (!(o instanceof Map.Entry))3906return false;3907return e.equals(new AbstractMap.SimpleImmutableEntry3908<>((Map.Entry<?,?>)o));3909}3910}3911}3912}39133914/**3915* Returns a dynamically typesafe view of the specified sorted map.3916* Any attempt to insert a mapping whose key or value have the wrong3917* type will result in an immediate {@link ClassCastException}.3918* Similarly, any attempt to modify the value currently associated with3919* a key will result in an immediate {@link ClassCastException},3920* whether the modification is attempted directly through the map3921* itself, or through a {@link Map.Entry} instance obtained from the3922* map's {@link Map#entrySet() entry set} view.3923*3924* <p>Assuming a map contains no incorrectly typed keys or values3925* prior to the time a dynamically typesafe view is generated, and3926* that all subsequent access to the map takes place through the view3927* (or one of its collection views), it is <i>guaranteed</i> that the3928* map cannot contain an incorrectly typed key or value.3929*3930* <p>A discussion of the use of dynamically typesafe views may be3931* found in the documentation for the {@link #checkedCollection3932* checkedCollection} method.3933*3934* <p>The returned map will be serializable if the specified map is3935* serializable.3936*3937* <p>Since {@code null} is considered to be a value of any reference3938* type, the returned map permits insertion of null keys or values3939* whenever the backing map does.3940*3941* @param <K> the class of the map keys3942* @param <V> the class of the map values3943* @param m the map for which a dynamically typesafe view is to be3944* returned3945* @param keyType the type of key that {@code m} is permitted to hold3946* @param valueType the type of value that {@code m} is permitted to hold3947* @return a dynamically typesafe view of the specified map3948* @since 1.53949*/3950public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,3951Class<K> keyType,3952Class<V> valueType) {3953return new CheckedSortedMap<>(m, keyType, valueType);3954}39553956/**3957* @serial include3958*/3959static class CheckedSortedMap<K,V> extends CheckedMap<K,V>3960implements SortedMap<K,V>, Serializable3961{3962private static final long serialVersionUID = 1599671320688067438L;39633964private final SortedMap<K, V> sm;39653966CheckedSortedMap(SortedMap<K, V> m,3967Class<K> keyType, Class<V> valueType) {3968super(m, keyType, valueType);3969sm = m;3970}39713972public Comparator<? super K> comparator() { return sm.comparator(); }3973public K firstKey() { return sm.firstKey(); }3974public K lastKey() { return sm.lastKey(); }39753976public SortedMap<K,V> subMap(K fromKey, K toKey) {3977return checkedSortedMap(sm.subMap(fromKey, toKey),3978keyType, valueType);3979}3980public SortedMap<K,V> headMap(K toKey) {3981return checkedSortedMap(sm.headMap(toKey), keyType, valueType);3982}3983public SortedMap<K,V> tailMap(K fromKey) {3984return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);3985}3986}39873988/**3989* Returns a dynamically typesafe view of the specified navigable map.3990* Any attempt to insert a mapping whose key or value have the wrong3991* type will result in an immediate {@link ClassCastException}.3992* Similarly, any attempt to modify the value currently associated with3993* a key will result in an immediate {@link ClassCastException},3994* whether the modification is attempted directly through the map3995* itself, or through a {@link Map.Entry} instance obtained from the3996* map's {@link Map#entrySet() entry set} view.3997*3998* <p>Assuming a map contains no incorrectly typed keys or values3999* prior to the time a dynamically typesafe view is generated, and4000* that all subsequent access to the map takes place through the view4001* (or one of its collection views), it is <em>guaranteed</em> that the4002* map cannot contain an incorrectly typed key or value.4003*4004* <p>A discussion of the use of dynamically typesafe views may be4005* found in the documentation for the {@link #checkedCollection4006* checkedCollection} method.4007*4008* <p>The returned map will be serializable if the specified map is4009* serializable.4010*4011* <p>Since {@code null} is considered to be a value of any reference4012* type, the returned map permits insertion of null keys or values4013* whenever the backing map does.4014*4015* @param <K> type of map keys4016* @param <V> type of map values4017* @param m the map for which a dynamically typesafe view is to be4018* returned4019* @param keyType the type of key that {@code m} is permitted to hold4020* @param valueType the type of value that {@code m} is permitted to hold4021* @return a dynamically typesafe view of the specified map4022* @since 1.84023*/4024public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m,4025Class<K> keyType,4026Class<V> valueType) {4027return new CheckedNavigableMap<>(m, keyType, valueType);4028}40294030/**4031* @serial include4032*/4033static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V>4034implements NavigableMap<K,V>, Serializable4035{4036private static final long serialVersionUID = -4852462692372534096L;40374038private final NavigableMap<K, V> nm;40394040CheckedNavigableMap(NavigableMap<K, V> m,4041Class<K> keyType, Class<V> valueType) {4042super(m, keyType, valueType);4043nm = m;4044}40454046public Comparator<? super K> comparator() { return nm.comparator(); }4047public K firstKey() { return nm.firstKey(); }4048public K lastKey() { return nm.lastKey(); }40494050public Entry<K, V> lowerEntry(K key) {4051Entry<K,V> lower = nm.lowerEntry(key);4052return (null != lower)4053? new CheckedMap.CheckedEntrySet.CheckedEntry<>(lower, valueType)4054: null;4055}40564057public K lowerKey(K key) { return nm.lowerKey(key); }40584059public Entry<K, V> floorEntry(K key) {4060Entry<K,V> floor = nm.floorEntry(key);4061return (null != floor)4062? new CheckedMap.CheckedEntrySet.CheckedEntry<>(floor, valueType)4063: null;4064}40654066public K floorKey(K key) { return nm.floorKey(key); }40674068public Entry<K, V> ceilingEntry(K key) {4069Entry<K,V> ceiling = nm.ceilingEntry(key);4070return (null != ceiling)4071? new CheckedMap.CheckedEntrySet.CheckedEntry<>(ceiling, valueType)4072: null;4073}40744075public K ceilingKey(K key) { return nm.ceilingKey(key); }40764077public Entry<K, V> higherEntry(K key) {4078Entry<K,V> higher = nm.higherEntry(key);4079return (null != higher)4080? new CheckedMap.CheckedEntrySet.CheckedEntry<>(higher, valueType)4081: null;4082}40834084public K higherKey(K key) { return nm.higherKey(key); }40854086public Entry<K, V> firstEntry() {4087Entry<K,V> first = nm.firstEntry();4088return (null != first)4089? new CheckedMap.CheckedEntrySet.CheckedEntry<>(first, valueType)4090: null;4091}40924093public Entry<K, V> lastEntry() {4094Entry<K,V> last = nm.lastEntry();4095return (null != last)4096? new CheckedMap.CheckedEntrySet.CheckedEntry<>(last, valueType)4097: null;4098}40994100public Entry<K, V> pollFirstEntry() {4101Entry<K,V> entry = nm.pollFirstEntry();4102return (null == entry)4103? null4104: new CheckedMap.CheckedEntrySet.CheckedEntry<>(entry, valueType);4105}41064107public Entry<K, V> pollLastEntry() {4108Entry<K,V> entry = nm.pollLastEntry();4109return (null == entry)4110? null4111: new CheckedMap.CheckedEntrySet.CheckedEntry<>(entry, valueType);4112}41134114public NavigableMap<K, V> descendingMap() {4115return checkedNavigableMap(nm.descendingMap(), keyType, valueType);4116}41174118public NavigableSet<K> keySet() {4119return navigableKeySet();4120}41214122public NavigableSet<K> navigableKeySet() {4123return checkedNavigableSet(nm.navigableKeySet(), keyType);4124}41254126public NavigableSet<K> descendingKeySet() {4127return checkedNavigableSet(nm.descendingKeySet(), keyType);4128}41294130@Override4131public NavigableMap<K,V> subMap(K fromKey, K toKey) {4132return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false),4133keyType, valueType);4134}41354136@Override4137public NavigableMap<K,V> headMap(K toKey) {4138return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType);4139}41404141@Override4142public NavigableMap<K,V> tailMap(K fromKey) {4143return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType);4144}41454146public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {4147return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType);4148}41494150public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {4151return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType);4152}41534154public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {4155return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType);4156}4157}41584159// Empty collections41604161/**4162* Returns an iterator that has no elements. More precisely,4163*4164* <ul>4165* <li>{@link Iterator#hasNext hasNext} always returns {@code4166* false}.</li>4167* <li>{@link Iterator#next next} always throws {@link4168* NoSuchElementException}.</li>4169* <li>{@link Iterator#remove remove} always throws {@link4170* IllegalStateException}.</li>4171* </ul>4172*4173* <p>Implementations of this method are permitted, but not4174* required, to return the same object from multiple invocations.4175*4176* @param <T> type of elements, if there were any, in the iterator4177* @return an empty iterator4178* @since 1.74179*/4180@SuppressWarnings("unchecked")4181public static <T> Iterator<T> emptyIterator() {4182return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;4183}41844185private static class EmptyIterator<E> implements Iterator<E> {4186static final EmptyIterator<Object> EMPTY_ITERATOR4187= new EmptyIterator<>();41884189public boolean hasNext() { return false; }4190public E next() { throw new NoSuchElementException(); }4191public void remove() { throw new IllegalStateException(); }4192@Override4193public void forEachRemaining(Consumer<? super E> action) {4194Objects.requireNonNull(action);4195}4196}41974198/**4199* Returns a list iterator that has no elements. More precisely,4200*4201* <ul>4202* <li>{@link Iterator#hasNext hasNext} and {@link4203* ListIterator#hasPrevious hasPrevious} always return {@code4204* false}.</li>4205* <li>{@link Iterator#next next} and {@link ListIterator#previous4206* previous} always throw {@link NoSuchElementException}.</li>4207* <li>{@link Iterator#remove remove} and {@link ListIterator#set4208* set} always throw {@link IllegalStateException}.</li>4209* <li>{@link ListIterator#add add} always throws {@link4210* UnsupportedOperationException}.</li>4211* <li>{@link ListIterator#nextIndex nextIndex} always returns4212* {@code 0}.</li>4213* <li>{@link ListIterator#previousIndex previousIndex} always4214* returns {@code -1}.</li>4215* </ul>4216*4217* <p>Implementations of this method are permitted, but not4218* required, to return the same object from multiple invocations.4219*4220* @param <T> type of elements, if there were any, in the iterator4221* @return an empty list iterator4222* @since 1.74223*/4224@SuppressWarnings("unchecked")4225public static <T> ListIterator<T> emptyListIterator() {4226return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR;4227}42284229private static class EmptyListIterator<E>4230extends EmptyIterator<E>4231implements ListIterator<E>4232{4233static final EmptyListIterator<Object> EMPTY_ITERATOR4234= new EmptyListIterator<>();42354236public boolean hasPrevious() { return false; }4237public E previous() { throw new NoSuchElementException(); }4238public int nextIndex() { return 0; }4239public int previousIndex() { return -1; }4240public void set(E e) { throw new IllegalStateException(); }4241public void add(E e) { throw new UnsupportedOperationException(); }4242}42434244/**4245* Returns an enumeration that has no elements. More precisely,4246*4247* <ul>4248* <li>{@link Enumeration#hasMoreElements hasMoreElements} always4249* returns {@code false}.</li>4250* <li> {@link Enumeration#nextElement nextElement} always throws4251* {@link NoSuchElementException}.</li>4252* </ul>4253*4254* <p>Implementations of this method are permitted, but not4255* required, to return the same object from multiple invocations.4256*4257* @param <T> the class of the objects in the enumeration4258* @return an empty enumeration4259* @since 1.74260*/4261@SuppressWarnings("unchecked")4262public static <T> Enumeration<T> emptyEnumeration() {4263return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;4264}42654266private static class EmptyEnumeration<E> implements Enumeration<E> {4267static final EmptyEnumeration<Object> EMPTY_ENUMERATION4268= new EmptyEnumeration<>();42694270public boolean hasMoreElements() { return false; }4271public E nextElement() { throw new NoSuchElementException(); }4272}42734274/**4275* The empty set (immutable). This set is serializable.4276*4277* @see #emptySet()4278*/4279@SuppressWarnings("rawtypes")4280public static final Set EMPTY_SET = new EmptySet<>();42814282/**4283* Returns an empty set (immutable). This set is serializable.4284* Unlike the like-named field, this method is parameterized.4285*4286* <p>This example illustrates the type-safe way to obtain an empty set:4287* <pre>4288* Set<String> s = Collections.emptySet();4289* </pre>4290* @implNote Implementations of this method need not create a separate4291* {@code Set} object for each call. Using this method is likely to have4292* comparable cost to using the like-named field. (Unlike this method, the4293* field does not provide type safety.)4294*4295* @param <T> the class of the objects in the set4296* @return the empty set4297*4298* @see #EMPTY_SET4299* @since 1.54300*/4301@SuppressWarnings("unchecked")4302public static final <T> Set<T> emptySet() {4303return (Set<T>) EMPTY_SET;4304}43054306/**4307* @serial include4308*/4309private static class EmptySet<E>4310extends AbstractSet<E>4311implements Serializable4312{4313private static final long serialVersionUID = 1582296315990362920L;43144315public Iterator<E> iterator() { return emptyIterator(); }43164317public int size() {return 0;}4318public boolean isEmpty() {return true;}43194320public boolean contains(Object obj) {return false;}4321public boolean containsAll(Collection<?> c) { return c.isEmpty(); }43224323public Object[] toArray() { return new Object[0]; }43244325public <T> T[] toArray(T[] a) {4326if (a.length > 0)4327a[0] = null;4328return a;4329}43304331// Override default methods in Collection4332@Override4333public void forEach(Consumer<? super E> action) {4334Objects.requireNonNull(action);4335}4336@Override4337public boolean removeIf(Predicate<? super E> filter) {4338Objects.requireNonNull(filter);4339return false;4340}4341@Override4342public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }43434344// Preserves singleton property4345private Object readResolve() {4346return EMPTY_SET;4347}4348}43494350/**4351* Returns an empty sorted set (immutable). This set is serializable.4352*4353* <p>This example illustrates the type-safe way to obtain an empty4354* sorted set:4355* <pre> {@code4356* SortedSet<String> s = Collections.emptySortedSet();4357* }</pre>4358*4359* @implNote Implementations of this method need not create a separate4360* {@code SortedSet} object for each call.4361*4362* @param <E> type of elements, if there were any, in the set4363* @return the empty sorted set4364* @since 1.84365*/4366@SuppressWarnings("unchecked")4367public static <E> SortedSet<E> emptySortedSet() {4368return (SortedSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;4369}43704371/**4372* Returns an empty navigable set (immutable). This set is serializable.4373*4374* <p>This example illustrates the type-safe way to obtain an empty4375* navigable set:4376* <pre> {@code4377* NavigableSet<String> s = Collections.emptyNavigableSet();4378* }</pre>4379*4380* @implNote Implementations of this method need not4381* create a separate {@code NavigableSet} object for each call.4382*4383* @param <E> type of elements, if there were any, in the set4384* @return the empty navigable set4385* @since 1.84386*/4387@SuppressWarnings("unchecked")4388public static <E> NavigableSet<E> emptyNavigableSet() {4389return (NavigableSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;4390}43914392/**4393* The empty list (immutable). This list is serializable.4394*4395* @see #emptyList()4396*/4397@SuppressWarnings("rawtypes")4398public static final List EMPTY_LIST = new EmptyList<>();43994400/**4401* Returns an empty list (immutable). This list is serializable.4402*4403* <p>This example illustrates the type-safe way to obtain an empty list:4404* <pre>4405* List<String> s = Collections.emptyList();4406* </pre>4407*4408* @implNote4409* Implementations of this method need not create a separate <tt>List</tt>4410* object for each call. Using this method is likely to have comparable4411* cost to using the like-named field. (Unlike this method, the field does4412* not provide type safety.)4413*4414* @param <T> type of elements, if there were any, in the list4415* @return an empty immutable list4416*4417* @see #EMPTY_LIST4418* @since 1.54419*/4420@SuppressWarnings("unchecked")4421public static final <T> List<T> emptyList() {4422return (List<T>) EMPTY_LIST;4423}44244425/**4426* @serial include4427*/4428private static class EmptyList<E>4429extends AbstractList<E>4430implements RandomAccess, Serializable {4431private static final long serialVersionUID = 8842843931221139166L;44324433public Iterator<E> iterator() {4434return emptyIterator();4435}4436public ListIterator<E> listIterator() {4437return emptyListIterator();4438}44394440public int size() {return 0;}4441public boolean isEmpty() {return true;}44424443public boolean contains(Object obj) {return false;}4444public boolean containsAll(Collection<?> c) { return c.isEmpty(); }44454446public Object[] toArray() { return new Object[0]; }44474448public <T> T[] toArray(T[] a) {4449if (a.length > 0)4450a[0] = null;4451return a;4452}44534454public E get(int index) {4455throw new IndexOutOfBoundsException("Index: "+index);4456}44574458public boolean equals(Object o) {4459return (o instanceof List) && ((List<?>)o).isEmpty();4460}44614462public int hashCode() { return 1; }44634464@Override4465public boolean removeIf(Predicate<? super E> filter) {4466Objects.requireNonNull(filter);4467return false;4468}4469@Override4470public void replaceAll(UnaryOperator<E> operator) {4471Objects.requireNonNull(operator);4472}4473@Override4474public void sort(Comparator<? super E> c) {4475}44764477// Override default methods in Collection4478@Override4479public void forEach(Consumer<? super E> action) {4480Objects.requireNonNull(action);4481}44824483@Override4484public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }44854486// Preserves singleton property4487private Object readResolve() {4488return EMPTY_LIST;4489}4490}44914492/**4493* The empty map (immutable). This map is serializable.4494*4495* @see #emptyMap()4496* @since 1.34497*/4498@SuppressWarnings("rawtypes")4499public static final Map EMPTY_MAP = new EmptyMap<>();45004501/**4502* Returns an empty map (immutable). This map is serializable.4503*4504* <p>This example illustrates the type-safe way to obtain an empty map:4505* <pre>4506* Map<String, Date> s = Collections.emptyMap();4507* </pre>4508* @implNote Implementations of this method need not create a separate4509* {@code Map} object for each call. Using this method is likely to have4510* comparable cost to using the like-named field. (Unlike this method, the4511* field does not provide type safety.)4512*4513* @param <K> the class of the map keys4514* @param <V> the class of the map values4515* @return an empty map4516* @see #EMPTY_MAP4517* @since 1.54518*/4519@SuppressWarnings("unchecked")4520public static final <K,V> Map<K,V> emptyMap() {4521return (Map<K,V>) EMPTY_MAP;4522}45234524/**4525* Returns an empty sorted map (immutable). This map is serializable.4526*4527* <p>This example illustrates the type-safe way to obtain an empty map:4528* <pre> {@code4529* SortedMap<String, Date> s = Collections.emptySortedMap();4530* }</pre>4531*4532* @implNote Implementations of this method need not create a separate4533* {@code SortedMap} object for each call.4534*4535* @param <K> the class of the map keys4536* @param <V> the class of the map values4537* @return an empty sorted map4538* @since 1.84539*/4540@SuppressWarnings("unchecked")4541public static final <K,V> SortedMap<K,V> emptySortedMap() {4542return (SortedMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;4543}45444545/**4546* Returns an empty navigable map (immutable). This map is serializable.4547*4548* <p>This example illustrates the type-safe way to obtain an empty map:4549* <pre> {@code4550* NavigableMap<String, Date> s = Collections.emptyNavigableMap();4551* }</pre>4552*4553* @implNote Implementations of this method need not create a separate4554* {@code NavigableMap} object for each call.4555*4556* @param <K> the class of the map keys4557* @param <V> the class of the map values4558* @return an empty navigable map4559* @since 1.84560*/4561@SuppressWarnings("unchecked")4562public static final <K,V> NavigableMap<K,V> emptyNavigableMap() {4563return (NavigableMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;4564}45654566/**4567* @serial include4568*/4569private static class EmptyMap<K,V>4570extends AbstractMap<K,V>4571implements Serializable4572{4573private static final long serialVersionUID = 6428348081105594320L;45744575public int size() {return 0;}4576public boolean isEmpty() {return true;}4577public boolean containsKey(Object key) {return false;}4578public boolean containsValue(Object value) {return false;}4579public V get(Object key) {return null;}4580public Set<K> keySet() {return emptySet();}4581public Collection<V> values() {return emptySet();}4582public Set<Map.Entry<K,V>> entrySet() {return emptySet();}45834584public boolean equals(Object o) {4585return (o instanceof Map) && ((Map<?,?>)o).isEmpty();4586}45874588public int hashCode() {return 0;}45894590// Override default methods in Map4591@Override4592@SuppressWarnings("unchecked")4593public V getOrDefault(Object k, V defaultValue) {4594return defaultValue;4595}45964597@Override4598public void forEach(BiConsumer<? super K, ? super V> action) {4599Objects.requireNonNull(action);4600}46014602@Override4603public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {4604Objects.requireNonNull(function);4605}46064607@Override4608public V putIfAbsent(K key, V value) {4609throw new UnsupportedOperationException();4610}46114612@Override4613public boolean remove(Object key, Object value) {4614throw new UnsupportedOperationException();4615}46164617@Override4618public boolean replace(K key, V oldValue, V newValue) {4619throw new UnsupportedOperationException();4620}46214622@Override4623public V replace(K key, V value) {4624throw new UnsupportedOperationException();4625}46264627@Override4628public V computeIfAbsent(K key,4629Function<? super K, ? extends V> mappingFunction) {4630throw new UnsupportedOperationException();4631}46324633@Override4634public V computeIfPresent(K key,4635BiFunction<? super K, ? super V, ? extends V> remappingFunction) {4636throw new UnsupportedOperationException();4637}46384639@Override4640public V compute(K key,4641BiFunction<? super K, ? super V, ? extends V> remappingFunction) {4642throw new UnsupportedOperationException();4643}46444645@Override4646public V merge(K key, V value,4647BiFunction<? super V, ? super V, ? extends V> remappingFunction) {4648throw new UnsupportedOperationException();4649}46504651// Preserves singleton property4652private Object readResolve() {4653return EMPTY_MAP;4654}4655}46564657// Singleton collections46584659/**4660* Returns an immutable set containing only the specified object.4661* The returned set is serializable.4662*4663* @param <T> the class of the objects in the set4664* @param o the sole object to be stored in the returned set.4665* @return an immutable set containing only the specified object.4666*/4667public static <T> Set<T> singleton(T o) {4668return new SingletonSet<>(o);4669}46704671static <E> Iterator<E> singletonIterator(final E e) {4672return new Iterator<E>() {4673private boolean hasNext = true;4674public boolean hasNext() {4675return hasNext;4676}4677public E next() {4678if (hasNext) {4679hasNext = false;4680return e;4681}4682throw new NoSuchElementException();4683}4684public void remove() {4685throw new UnsupportedOperationException();4686}4687@Override4688public void forEachRemaining(Consumer<? super E> action) {4689Objects.requireNonNull(action);4690if (hasNext) {4691action.accept(e);4692hasNext = false;4693}4694}4695};4696}46974698/**4699* Creates a {@code Spliterator} with only the specified element4700*4701* @param <T> Type of elements4702* @return A singleton {@code Spliterator}4703*/4704static <T> Spliterator<T> singletonSpliterator(final T element) {4705return new Spliterator<T>() {4706long est = 1;47074708@Override4709public Spliterator<T> trySplit() {4710return null;4711}47124713@Override4714public boolean tryAdvance(Consumer<? super T> consumer) {4715Objects.requireNonNull(consumer);4716if (est > 0) {4717est--;4718consumer.accept(element);4719return true;4720}4721return false;4722}47234724@Override4725public void forEachRemaining(Consumer<? super T> consumer) {4726tryAdvance(consumer);4727}47284729@Override4730public long estimateSize() {4731return est;4732}47334734@Override4735public int characteristics() {4736int value = (element != null) ? Spliterator.NONNULL : 0;47374738return value | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE |4739Spliterator.DISTINCT | Spliterator.ORDERED;4740}4741};4742}47434744/**4745* @serial include4746*/4747private static class SingletonSet<E>4748extends AbstractSet<E>4749implements Serializable4750{4751private static final long serialVersionUID = 3193687207550431679L;47524753private final E element;47544755SingletonSet(E e) {element = e;}47564757public Iterator<E> iterator() {4758return singletonIterator(element);4759}47604761public int size() {return 1;}47624763public boolean contains(Object o) {return eq(o, element);}47644765// Override default methods for Collection4766@Override4767public void forEach(Consumer<? super E> action) {4768action.accept(element);4769}4770@Override4771public Spliterator<E> spliterator() {4772return singletonSpliterator(element);4773}4774@Override4775public boolean removeIf(Predicate<? super E> filter) {4776throw new UnsupportedOperationException();4777}4778}47794780/**4781* Returns an immutable list containing only the specified object.4782* The returned list is serializable.4783*4784* @param <T> the class of the objects in the list4785* @param o the sole object to be stored in the returned list.4786* @return an immutable list containing only the specified object.4787* @since 1.34788*/4789public static <T> List<T> singletonList(T o) {4790return new SingletonList<>(o);4791}47924793/**4794* @serial include4795*/4796private static class SingletonList<E>4797extends AbstractList<E>4798implements RandomAccess, Serializable {47994800private static final long serialVersionUID = 3093736618740652951L;48014802private final E element;48034804SingletonList(E obj) {element = obj;}48054806public Iterator<E> iterator() {4807return singletonIterator(element);4808}48094810public int size() {return 1;}48114812public boolean contains(Object obj) {return eq(obj, element);}48134814public E get(int index) {4815if (index != 0)4816throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");4817return element;4818}48194820// Override default methods for Collection4821@Override4822public void forEach(Consumer<? super E> action) {4823action.accept(element);4824}4825@Override4826public boolean removeIf(Predicate<? super E> filter) {4827throw new UnsupportedOperationException();4828}4829@Override4830public void replaceAll(UnaryOperator<E> operator) {4831throw new UnsupportedOperationException();4832}4833@Override4834public void sort(Comparator<? super E> c) {4835}4836@Override4837public Spliterator<E> spliterator() {4838return singletonSpliterator(element);4839}4840}48414842/**4843* Returns an immutable map, mapping only the specified key to the4844* specified value. The returned map is serializable.4845*4846* @param <K> the class of the map keys4847* @param <V> the class of the map values4848* @param key the sole key to be stored in the returned map.4849* @param value the value to which the returned map maps <tt>key</tt>.4850* @return an immutable map containing only the specified key-value4851* mapping.4852* @since 1.34853*/4854public static <K,V> Map<K,V> singletonMap(K key, V value) {4855return new SingletonMap<>(key, value);4856}48574858/**4859* @serial include4860*/4861private static class SingletonMap<K,V>4862extends AbstractMap<K,V>4863implements Serializable {4864private static final long serialVersionUID = -6979724477215052911L;48654866private final K k;4867private final V v;48684869SingletonMap(K key, V value) {4870k = key;4871v = value;4872}48734874public int size() {return 1;}4875public boolean isEmpty() {return false;}4876public boolean containsKey(Object key) {return eq(key, k);}4877public boolean containsValue(Object value) {return eq(value, v);}4878public V get(Object key) {return (eq(key, k) ? v : null);}48794880private transient Set<K> keySet;4881private transient Set<Map.Entry<K,V>> entrySet;4882private transient Collection<V> values;48834884public Set<K> keySet() {4885if (keySet==null)4886keySet = singleton(k);4887return keySet;4888}48894890public Set<Map.Entry<K,V>> entrySet() {4891if (entrySet==null)4892entrySet = Collections.<Map.Entry<K,V>>singleton(4893new SimpleImmutableEntry<>(k, v));4894return entrySet;4895}48964897public Collection<V> values() {4898if (values==null)4899values = singleton(v);4900return values;4901}49024903// Override default methods in Map4904@Override4905public V getOrDefault(Object key, V defaultValue) {4906return eq(key, k) ? v : defaultValue;4907}49084909@Override4910public void forEach(BiConsumer<? super K, ? super V> action) {4911action.accept(k, v);4912}49134914@Override4915public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {4916throw new UnsupportedOperationException();4917}49184919@Override4920public V putIfAbsent(K key, V value) {4921throw new UnsupportedOperationException();4922}49234924@Override4925public boolean remove(Object key, Object value) {4926throw new UnsupportedOperationException();4927}49284929@Override4930public boolean replace(K key, V oldValue, V newValue) {4931throw new UnsupportedOperationException();4932}49334934@Override4935public V replace(K key, V value) {4936throw new UnsupportedOperationException();4937}49384939@Override4940public V computeIfAbsent(K key,4941Function<? super K, ? extends V> mappingFunction) {4942throw new UnsupportedOperationException();4943}49444945@Override4946public V computeIfPresent(K key,4947BiFunction<? super K, ? super V, ? extends V> remappingFunction) {4948throw new UnsupportedOperationException();4949}49504951@Override4952public V compute(K key,4953BiFunction<? super K, ? super V, ? extends V> remappingFunction) {4954throw new UnsupportedOperationException();4955}49564957@Override4958public V merge(K key, V value,4959BiFunction<? super V, ? super V, ? extends V> remappingFunction) {4960throw new UnsupportedOperationException();4961}4962}49634964// Miscellaneous49654966/**4967* Returns an immutable list consisting of <tt>n</tt> copies of the4968* specified object. The newly allocated data object is tiny (it contains4969* a single reference to the data object). This method is useful in4970* combination with the <tt>List.addAll</tt> method to grow lists.4971* The returned list is serializable.4972*4973* @param <T> the class of the object to copy and of the objects4974* in the returned list.4975* @param n the number of elements in the returned list.4976* @param o the element to appear repeatedly in the returned list.4977* @return an immutable list consisting of <tt>n</tt> copies of the4978* specified object.4979* @throws IllegalArgumentException if {@code n < 0}4980* @see List#addAll(Collection)4981* @see List#addAll(int, Collection)4982*/4983public static <T> List<T> nCopies(int n, T o) {4984if (n < 0)4985throw new IllegalArgumentException("List length = " + n);4986return new CopiesList<>(n, o);4987}49884989/**4990* @serial include4991*/4992private static class CopiesList<E>4993extends AbstractList<E>4994implements RandomAccess, Serializable4995{4996private static final long serialVersionUID = 2739099268398711800L;49974998final int n;4999final E element;50005001CopiesList(int n, E e) {5002assert n >= 0;5003this.n = n;5004element = e;5005}50065007public int size() {5008return n;5009}50105011public boolean contains(Object obj) {5012return n != 0 && eq(obj, element);5013}50145015public int indexOf(Object o) {5016return contains(o) ? 0 : -1;5017}50185019public int lastIndexOf(Object o) {5020return contains(o) ? n - 1 : -1;5021}50225023public E get(int index) {5024if (index < 0 || index >= n)5025throw new IndexOutOfBoundsException("Index: "+index+5026", Size: "+n);5027return element;5028}50295030public Object[] toArray() {5031final Object[] a = new Object[n];5032if (element != null)5033Arrays.fill(a, 0, n, element);5034return a;5035}50365037@SuppressWarnings("unchecked")5038public <T> T[] toArray(T[] a) {5039final int n = this.n;5040if (a.length < n) {5041a = (T[])java.lang.reflect.Array5042.newInstance(a.getClass().getComponentType(), n);5043if (element != null)5044Arrays.fill(a, 0, n, element);5045} else {5046Arrays.fill(a, 0, n, element);5047if (a.length > n)5048a[n] = null;5049}5050return a;5051}50525053public List<E> subList(int fromIndex, int toIndex) {5054if (fromIndex < 0)5055throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);5056if (toIndex > n)5057throw new IndexOutOfBoundsException("toIndex = " + toIndex);5058if (fromIndex > toIndex)5059throw new IllegalArgumentException("fromIndex(" + fromIndex +5060") > toIndex(" + toIndex + ")");5061return new CopiesList<>(toIndex - fromIndex, element);5062}50635064@Override5065public int hashCode() {5066if (n == 0) return 1;5067// hashCode of n repeating elements is 31^n + elementHash * Sum(31^k, k = 0..n-1)5068// this implementation completes in O(log(n)) steps taking advantage of5069// 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)5070int pow = 31;5071int sum = 1;5072for (int i = Integer.numberOfLeadingZeros(n) + 1; i < Integer.SIZE; i++) {5073sum *= pow + 1;5074pow *= pow;5075if ((n << i) < 0) {5076pow *= 31;5077sum = sum * 31 + 1;5078}5079}5080return pow + sum * (element == null ? 0 : element.hashCode());5081}50825083@Override5084public boolean equals(Object o) {5085if (o == this)5086return true;5087if (o instanceof CopiesList) {5088CopiesList<?> other = (CopiesList<?>) o;5089return n == other.n && (n == 0 || eq(element, other.element));5090}5091if (!(o instanceof List))5092return false;50935094int remaining = n;5095E e = element;5096Iterator<?> itr = ((List<?>) o).iterator();5097if (e == null) {5098while (itr.hasNext() && remaining-- > 0) {5099if (itr.next() != null)5100return false;5101}5102} else {5103while (itr.hasNext() && remaining-- > 0) {5104if (!e.equals(itr.next()))5105return false;5106}5107}5108return remaining == 0 && !itr.hasNext();5109}51105111// Override default methods in Collection5112@Override5113public Stream<E> stream() {5114return IntStream.range(0, n).mapToObj(i -> element);5115}51165117@Override5118public Stream<E> parallelStream() {5119return IntStream.range(0, n).parallel().mapToObj(i -> element);5120}51215122@Override5123public Spliterator<E> spliterator() {5124return stream().spliterator();5125}51265127private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {5128ois.defaultReadObject();5129SharedSecrets.getJavaOISAccess().checkArray(ois, Object[].class, n);5130}5131}51325133/**5134* Returns a comparator that imposes the reverse of the <em>natural5135* ordering</em> on a collection of objects that implement the5136* {@code Comparable} interface. (The natural ordering is the ordering5137* imposed by the objects' own {@code compareTo} method.) This enables a5138* simple idiom for sorting (or maintaining) collections (or arrays) of5139* objects that implement the {@code Comparable} interface in5140* reverse-natural-order. For example, suppose {@code a} is an array of5141* strings. Then: <pre>5142* Arrays.sort(a, Collections.reverseOrder());5143* </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>5144*5145* The returned comparator is serializable.5146*5147* @param <T> the class of the objects compared by the comparator5148* @return A comparator that imposes the reverse of the <i>natural5149* ordering</i> on a collection of objects that implement5150* the <tt>Comparable</tt> interface.5151* @see Comparable5152*/5153@SuppressWarnings("unchecked")5154public static <T> Comparator<T> reverseOrder() {5155return (Comparator<T>) ReverseComparator.REVERSE_ORDER;5156}51575158/**5159* @serial include5160*/5161private static class ReverseComparator5162implements Comparator<Comparable<Object>>, Serializable {51635164private static final long serialVersionUID = 7207038068494060240L;51655166static final ReverseComparator REVERSE_ORDER5167= new ReverseComparator();51685169public int compare(Comparable<Object> c1, Comparable<Object> c2) {5170return c2.compareTo(c1);5171}51725173private Object readResolve() { return Collections.reverseOrder(); }51745175@Override5176public Comparator<Comparable<Object>> reversed() {5177return Comparator.naturalOrder();5178}5179}51805181/**5182* Returns a comparator that imposes the reverse ordering of the specified5183* comparator. If the specified comparator is {@code null}, this method is5184* equivalent to {@link #reverseOrder()} (in other words, it returns a5185* comparator that imposes the reverse of the <em>natural ordering</em> on5186* a collection of objects that implement the Comparable interface).5187*5188* <p>The returned comparator is serializable (assuming the specified5189* comparator is also serializable or {@code null}).5190*5191* @param <T> the class of the objects compared by the comparator5192* @param cmp a comparator who's ordering is to be reversed by the returned5193* comparator or {@code null}5194* @return A comparator that imposes the reverse ordering of the5195* specified comparator.5196* @since 1.55197*/5198public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {5199if (cmp == null)5200return reverseOrder();52015202if (cmp instanceof ReverseComparator2)5203return ((ReverseComparator2<T>)cmp).cmp;52045205return new ReverseComparator2<>(cmp);5206}52075208/**5209* @serial include5210*/5211private static class ReverseComparator2<T> implements Comparator<T>,5212Serializable5213{5214private static final long serialVersionUID = 4374092139857L;52155216/**5217* The comparator specified in the static factory. This will never5218* be null, as the static factory returns a ReverseComparator5219* instance if its argument is null.5220*5221* @serial5222*/5223final Comparator<T> cmp;52245225ReverseComparator2(Comparator<T> cmp) {5226assert cmp != null;5227this.cmp = cmp;5228}52295230public int compare(T t1, T t2) {5231return cmp.compare(t2, t1);5232}52335234public boolean equals(Object o) {5235return (o == this) ||5236(o instanceof ReverseComparator2 &&5237cmp.equals(((ReverseComparator2)o).cmp));5238}52395240public int hashCode() {5241return cmp.hashCode() ^ Integer.MIN_VALUE;5242}52435244@Override5245public Comparator<T> reversed() {5246return cmp;5247}5248}52495250/**5251* Returns an enumeration over the specified collection. This provides5252* interoperability with legacy APIs that require an enumeration5253* as input.5254*5255* @param <T> the class of the objects in the collection5256* @param c the collection for which an enumeration is to be returned.5257* @return an enumeration over the specified collection.5258* @see Enumeration5259*/5260public static <T> Enumeration<T> enumeration(final Collection<T> c) {5261return new Enumeration<T>() {5262private final Iterator<T> i = c.iterator();52635264public boolean hasMoreElements() {5265return i.hasNext();5266}52675268public T nextElement() {5269return i.next();5270}5271};5272}52735274/**5275* Returns an array list containing the elements returned by the5276* specified enumeration in the order they are returned by the5277* enumeration. This method provides interoperability between5278* legacy APIs that return enumerations and new APIs that require5279* collections.5280*5281* @param <T> the class of the objects returned by the enumeration5282* @param e enumeration providing elements for the returned5283* array list5284* @return an array list containing the elements returned5285* by the specified enumeration.5286* @since 1.45287* @see Enumeration5288* @see ArrayList5289*/5290public static <T> ArrayList<T> list(Enumeration<T> e) {5291ArrayList<T> l = new ArrayList<>();5292while (e.hasMoreElements())5293l.add(e.nextElement());5294return l;5295}52965297/**5298* Returns true if the specified arguments are equal, or both null.5299*5300* NB: Do not replace with Object.equals until JDK-8015417 is resolved.5301*/5302static boolean eq(Object o1, Object o2) {5303return o1==null ? o2==null : o1.equals(o2);5304}53055306/**5307* Returns the number of elements in the specified collection equal to the5308* specified object. More formally, returns the number of elements5309* <tt>e</tt> in the collection such that5310* <tt>(o == null ? e == null : o.equals(e))</tt>.5311*5312* @param c the collection in which to determine the frequency5313* of <tt>o</tt>5314* @param o the object whose frequency is to be determined5315* @return the number of elements in {@code c} equal to {@code o}5316* @throws NullPointerException if <tt>c</tt> is null5317* @since 1.55318*/5319public static int frequency(Collection<?> c, Object o) {5320int result = 0;5321if (o == null) {5322for (Object e : c)5323if (e == null)5324result++;5325} else {5326for (Object e : c)5327if (o.equals(e))5328result++;5329}5330return result;5331}53325333/**5334* Returns {@code true} if the two specified collections have no5335* elements in common.5336*5337* <p>Care must be exercised if this method is used on collections that5338* do not comply with the general contract for {@code Collection}.5339* Implementations may elect to iterate over either collection and test5340* for containment in the other collection (or to perform any equivalent5341* computation). If either collection uses a nonstandard equality test5342* (as does a {@link SortedSet} whose ordering is not <em>compatible with5343* equals</em>, or the key set of an {@link IdentityHashMap}), both5344* collections must use the same nonstandard equality test, or the5345* result of this method is undefined.5346*5347* <p>Care must also be exercised when using collections that have5348* restrictions on the elements that they may contain. Collection5349* implementations are allowed to throw exceptions for any operation5350* involving elements they deem ineligible. For absolute safety the5351* specified collections should contain only elements which are5352* eligible elements for both collections.5353*5354* <p>Note that it is permissible to pass the same collection in both5355* parameters, in which case the method will return {@code true} if and5356* only if the collection is empty.5357*5358* @param c1 a collection5359* @param c2 a collection5360* @return {@code true} if the two specified collections have no5361* elements in common.5362* @throws NullPointerException if either collection is {@code null}.5363* @throws NullPointerException if one collection contains a {@code null}5364* element and {@code null} is not an eligible element for the other collection.5365* (<a href="Collection.html#optional-restrictions">optional</a>)5366* @throws ClassCastException if one collection contains an element that is5367* of a type which is ineligible for the other collection.5368* (<a href="Collection.html#optional-restrictions">optional</a>)5369* @since 1.55370*/5371public static boolean disjoint(Collection<?> c1, Collection<?> c2) {5372// The collection to be used for contains(). Preference is given to5373// the collection who's contains() has lower O() complexity.5374Collection<?> contains = c2;5375// The collection to be iterated. If the collections' contains() impl5376// are of different O() complexity, the collection with slower5377// contains() will be used for iteration. For collections who's5378// contains() are of the same complexity then best performance is5379// achieved by iterating the smaller collection.5380Collection<?> iterate = c1;53815382// Performance optimization cases. The heuristics:5383// 1. Generally iterate over c1.5384// 2. If c1 is a Set then iterate over c2.5385// 3. If either collection is empty then result is always true.5386// 4. Iterate over the smaller Collection.5387if (c1 instanceof Set) {5388// Use c1 for contains as a Set's contains() is expected to perform5389// better than O(N/2)5390iterate = c2;5391contains = c1;5392} else if (!(c2 instanceof Set)) {5393// Both are mere Collections. Iterate over smaller collection.5394// Example: If c1 contains 3 elements and c2 contains 50 elements and5395// assuming contains() requires ceiling(N/2) comparisons then5396// checking for all c1 elements in c2 would require 75 comparisons5397// (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring5398// 100 comparisons (50 * ceiling(3/2)).5399int c1size = c1.size();5400int c2size = c2.size();5401if (c1size == 0 || c2size == 0) {5402// At least one collection is empty. Nothing will match.5403return true;5404}54055406if (c1size > c2size) {5407iterate = c2;5408contains = c1;5409}5410}54115412for (Object e : iterate) {5413if (contains.contains(e)) {5414// Found a common element. Collections are not disjoint.5415return false;5416}5417}54185419// No common elements were found.5420return true;5421}54225423/**5424* Adds all of the specified elements to the specified collection.5425* Elements to be added may be specified individually or as an array.5426* The behavior of this convenience method is identical to that of5427* <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely5428* to run significantly faster under most implementations.5429*5430* <p>When elements are specified individually, this method provides a5431* convenient way to add a few elements to an existing collection:5432* <pre>5433* Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");5434* </pre>5435*5436* @param <T> the class of the elements to add and of the collection5437* @param c the collection into which <tt>elements</tt> are to be inserted5438* @param elements the elements to insert into <tt>c</tt>5439* @return <tt>true</tt> if the collection changed as a result of the call5440* @throws UnsupportedOperationException if <tt>c</tt> does not support5441* the <tt>add</tt> operation5442* @throws NullPointerException if <tt>elements</tt> contains one or more5443* null values and <tt>c</tt> does not permit null elements, or5444* if <tt>c</tt> or <tt>elements</tt> are <tt>null</tt>5445* @throws IllegalArgumentException if some property of a value in5446* <tt>elements</tt> prevents it from being added to <tt>c</tt>5447* @see Collection#addAll(Collection)5448* @since 1.55449*/5450@SafeVarargs5451public static <T> boolean addAll(Collection<? super T> c, T... elements) {5452boolean result = false;5453for (T element : elements)5454result |= c.add(element);5455return result;5456}54575458/**5459* Returns a set backed by the specified map. The resulting set displays5460* the same ordering, concurrency, and performance characteristics as the5461* backing map. In essence, this factory method provides a {@link Set}5462* implementation corresponding to any {@link Map} implementation. There5463* is no need to use this method on a {@link Map} implementation that5464* already has a corresponding {@link Set} implementation (such as {@link5465* HashMap} or {@link TreeMap}).5466*5467* <p>Each method invocation on the set returned by this method results in5468* exactly one method invocation on the backing map or its <tt>keySet</tt>5469* view, with one exception. The <tt>addAll</tt> method is implemented5470* as a sequence of <tt>put</tt> invocations on the backing map.5471*5472* <p>The specified map must be empty at the time this method is invoked,5473* and should not be accessed directly after this method returns. These5474* conditions are ensured if the map is created empty, passed directly5475* to this method, and no reference to the map is retained, as illustrated5476* in the following code fragment:5477* <pre>5478* Set<Object> weakHashSet = Collections.newSetFromMap(5479* new WeakHashMap<Object, Boolean>());5480* </pre>5481*5482* @param <E> the class of the map keys and of the objects in the5483* returned set5484* @param map the backing map5485* @return the set backed by the map5486* @throws IllegalArgumentException if <tt>map</tt> is not empty5487* @since 1.65488*/5489public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {5490return new SetFromMap<>(map);5491}54925493/**5494* @serial include5495*/5496private static class SetFromMap<E> extends AbstractSet<E>5497implements Set<E>, Serializable5498{5499private final Map<E, Boolean> m; // The backing map5500private transient Set<E> s; // Its keySet55015502SetFromMap(Map<E, Boolean> map) {5503if (!map.isEmpty())5504throw new IllegalArgumentException("Map is non-empty");5505m = map;5506s = map.keySet();5507}55085509public void clear() { m.clear(); }5510public int size() { return m.size(); }5511public boolean isEmpty() { return m.isEmpty(); }5512public boolean contains(Object o) { return m.containsKey(o); }5513public boolean remove(Object o) { return m.remove(o) != null; }5514public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }5515public Iterator<E> iterator() { return s.iterator(); }5516public Object[] toArray() { return s.toArray(); }5517public <T> T[] toArray(T[] a) { return s.toArray(a); }5518public String toString() { return s.toString(); }5519public int hashCode() { return s.hashCode(); }5520public boolean equals(Object o) { return o == this || s.equals(o); }5521public boolean containsAll(Collection<?> c) {return s.containsAll(c);}5522public boolean removeAll(Collection<?> c) {return s.removeAll(c);}5523public boolean retainAll(Collection<?> c) {return s.retainAll(c);}5524// addAll is the only inherited implementation55255526// Override default methods in Collection5527@Override5528public void forEach(Consumer<? super E> action) {5529s.forEach(action);5530}5531@Override5532public boolean removeIf(Predicate<? super E> filter) {5533return s.removeIf(filter);5534}55355536@Override5537public Spliterator<E> spliterator() {return s.spliterator();}5538@Override5539public Stream<E> stream() {return s.stream();}5540@Override5541public Stream<E> parallelStream() {return s.parallelStream();}55425543private static final long serialVersionUID = 2454657854757543876L;55445545private void readObject(java.io.ObjectInputStream stream)5546throws IOException, ClassNotFoundException5547{5548stream.defaultReadObject();5549s = m.keySet();5550}5551}55525553/**5554* Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)5555* {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>,5556* <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This5557* view can be useful when you would like to use a method5558* requiring a <tt>Queue</tt> but you need Lifo ordering.5559*5560* <p>Each method invocation on the queue returned by this method5561* results in exactly one method invocation on the backing deque, with5562* one exception. The {@link Queue#addAll addAll} method is5563* implemented as a sequence of {@link Deque#addFirst addFirst}5564* invocations on the backing deque.5565*5566* @param <T> the class of the objects in the deque5567* @param deque the deque5568* @return the queue5569* @since 1.65570*/5571public static <T> Queue<T> asLifoQueue(Deque<T> deque) {5572return new AsLIFOQueue<>(deque);5573}55745575/**5576* @serial include5577*/5578static class AsLIFOQueue<E> extends AbstractQueue<E>5579implements Queue<E>, Serializable {5580private static final long serialVersionUID = 1802017725587941708L;5581private final Deque<E> q;5582AsLIFOQueue(Deque<E> q) { this.q = q; }5583public boolean add(E e) { q.addFirst(e); return true; }5584public boolean offer(E e) { return q.offerFirst(e); }5585public E poll() { return q.pollFirst(); }5586public E remove() { return q.removeFirst(); }5587public E peek() { return q.peekFirst(); }5588public E element() { return q.getFirst(); }5589public void clear() { q.clear(); }5590public int size() { return q.size(); }5591public boolean isEmpty() { return q.isEmpty(); }5592public boolean contains(Object o) { return q.contains(o); }5593public boolean remove(Object o) { return q.remove(o); }5594public Iterator<E> iterator() { return q.iterator(); }5595public Object[] toArray() { return q.toArray(); }5596public <T> T[] toArray(T[] a) { return q.toArray(a); }5597public String toString() { return q.toString(); }5598public boolean containsAll(Collection<?> c) {return q.containsAll(c);}5599public boolean removeAll(Collection<?> c) {return q.removeAll(c);}5600public boolean retainAll(Collection<?> c) {return q.retainAll(c);}5601// We use inherited addAll; forwarding addAll would be wrong56025603// Override default methods in Collection5604@Override5605public void forEach(Consumer<? super E> action) {q.forEach(action);}5606@Override5607public boolean removeIf(Predicate<? super E> filter) {5608return q.removeIf(filter);5609}5610@Override5611public Spliterator<E> spliterator() {return q.spliterator();}5612@Override5613public Stream<E> stream() {return q.stream();}5614@Override5615public Stream<E> parallelStream() {return q.parallelStream();}5616}5617}561856195620