• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.util;
28 
29 import java.io.IOException;
30 import java.io.ObjectInputStream;
31 import java.io.ObjectOutputStream;
32 import java.io.Serializable;
33 import java.lang.reflect.Array;
34 import java.util.function.BiConsumer;
35 import java.util.function.BiFunction;
36 import java.util.function.Consumer;
37 import java.util.function.Function;
38 import java.util.function.IntFunction;
39 import java.util.function.Predicate;
40 import java.util.function.UnaryOperator;
41 import java.util.stream.IntStream;
42 import java.util.stream.Stream;
43 import java.util.stream.StreamSupport;
44 // Android-changed: SharedSecrets are not moved yet.
45 // import jdk.internal.access.SharedSecrets;
46 import jdk.internal.misc.SharedSecrets;
47 
48 import dalvik.system.VMRuntime;
49 
50 /**
51  * This class consists exclusively of static methods that operate on or return
52  * collections.  It contains polymorphic algorithms that operate on
53  * collections, "wrappers", which return a new collection backed by a
54  * specified collection, and a few other odds and ends.
55  *
56  * <p>The methods of this class all throw a {@code NullPointerException}
57  * if the collections or class objects provided to them are null.
58  *
59  * <p>The documentation for the polymorphic algorithms contained in this class
60  * generally includes a brief description of the <i>implementation</i>.  Such
61  * descriptions should be regarded as <i>implementation notes</i>, rather than
62  * parts of the <i>specification</i>.  Implementors should feel free to
63  * substitute other algorithms, so long as the specification itself is adhered
64  * to.  (For example, the algorithm used by {@code sort} does not have to be
65  * a mergesort, but it does have to be <i>stable</i>.)
66  *
67  * <p>The "destructive" algorithms contained in this class, that is, the
68  * algorithms that modify the collection on which they operate, are specified
69  * to throw {@code UnsupportedOperationException} if the collection does not
70  * support the appropriate mutation primitive(s), such as the {@code set}
71  * method.  These algorithms may, but are not required to, throw this
72  * exception if an invocation would have no effect on the collection.  For
73  * example, invoking the {@code sort} method on an unmodifiable list that is
74  * already sorted may or may not throw {@code UnsupportedOperationException}.
75  *
76  * <p>This class is a member of the
77  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
78  * Java Collections Framework</a>.
79  *
80  * @author  Josh Bloch
81  * @author  Neal Gafter
82  * @see     Collection
83  * @see     Set
84  * @see     List
85  * @see     Map
86  * @since   1.2
87  */
88 
89 public class Collections {
90     // Suppresses default constructor, ensuring non-instantiability.
Collections()91     private Collections() {
92     }
93 
94     // Algorithms
95 
96     /*
97      * Tuning parameters for algorithms - Many of the List algorithms have
98      * two implementations, one of which is appropriate for RandomAccess
99      * lists, the other for "sequential."  Often, the random access variant
100      * yields better performance on small sequential access lists.  The
101      * tuning parameters below determine the cutoff point for what constitutes
102      * a "small" sequential access list for each algorithm.  The values below
103      * were empirically determined to work well for LinkedList. Hopefully
104      * they should be reasonable for other sequential access List
105      * implementations.  Those doing performance work on this code would
106      * do well to validate the values of these parameters from time to time.
107      * (The first word of each tuning parameter name is the algorithm to which
108      * it applies.)
109      */
110     private static final int BINARYSEARCH_THRESHOLD   = 5000;
111     private static final int REVERSE_THRESHOLD        =   18;
112     private static final int SHUFFLE_THRESHOLD        =    5;
113     private static final int FILL_THRESHOLD           =   25;
114     private static final int ROTATE_THRESHOLD         =  100;
115     private static final int COPY_THRESHOLD           =   10;
116     private static final int REPLACEALL_THRESHOLD     =   11;
117     private static final int INDEXOFSUBLIST_THRESHOLD =   35;
118 
119     // Android-added: List.sort() vs. Collections.sort() app compat.
120     // Added a warning in the documentation.
121     // Collections.sort() calls List.sort() for apps targeting API version >= 26
122     // (Android Oreo) but the other way around for app targeting <= 25 (Nougat).
123     /**
124      * Sorts the specified list into ascending order, according to the
125      * {@linkplain Comparable natural ordering} of its elements.
126      * All elements in the list must implement the {@link Comparable}
127      * interface.  Furthermore, all elements in the list must be
128      * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}
129      * must not throw a {@code ClassCastException} for any elements
130      * {@code e1} and {@code e2} in the list).
131      *
132      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
133      * not be reordered as a result of the sort.
134      *
135      * <p>The specified list must be modifiable, but need not be resizable.
136      *
137      * @implNote
138      * This implementation defers to the {@link List#sort(Comparator)}
139      * method using the specified list and a {@code null} comparator.
140      * Do not call this method from {@code List.sort()} since that can lead
141      * to infinite recursion. Apps targeting APIs {@code <= 25} observe
142      * backwards compatibility behavior where this method was implemented
143      * on top of {@link List#toArray()}, {@link ListIterator#next()} and
144      * {@link ListIterator#set(Object)}.
145      *
146      * @param  <T> the class of the objects in the list
147      * @param  list the list to be sorted.
148      * @throws ClassCastException if the list contains elements that are not
149      *         <i>mutually comparable</i> (for example, strings and integers).
150      * @throws UnsupportedOperationException if the specified list's
151      *         list-iterator does not support the {@code set} operation.
152      * @throws IllegalArgumentException (optional) if the implementation
153      *         detects that the natural ordering of the list elements is
154      *         found to violate the {@link Comparable} contract
155      * @see List#sort(Comparator)
156      */
157     @SuppressWarnings("unchecked")
sort(List<T> list)158     public static <T extends Comparable<? super T>> void sort(List<T> list) {
159         // Android-changed: List.sort() vs. Collections.sort() app compat.
160         // Call sort(list, null) here to be consistent with that method's
161         // (changed on Android) behavior.
162         // list.sort(null);
163         sort(list, null);
164     }
165 
166     // Android-added: List.sort() vs. Collections.sort() app compat.
167     // Added a warning in the documentation.
168     // Collections.sort() calls List.sort() for apps targeting API version >= 26
169     // (Android Oreo) but the other way around for app targeting <= 25 (Nougat).
170     /**
171      * Sorts the specified list according to the order induced by the
172      * specified comparator.  All elements in the list must be <i>mutually
173      * comparable</i> using the specified comparator (that is,
174      * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
175      * for any elements {@code e1} and {@code e2} in the list).
176      *
177      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
178      * not be reordered as a result of the sort.
179      *
180      * <p>The specified list must be modifiable, but need not be resizable.
181      *
182      * @implNote
183      * This implementation defers to the {@link List#sort(Comparator)}
184      * method using the specified list and comparator.
185      * Do not call this method from {@code List.sort()} since that can lead
186      * to infinite recursion. Apps targeting APIs {@code <= 25} observe
187      * backwards compatibility behavior where this method was implemented
188      * on top of {@link List#toArray()}, {@link ListIterator#next()} and
189      * {@link ListIterator#set(Object)}.
190      *
191      * @param  <T> the class of the objects in the list
192      * @param  list the list to be sorted.
193      * @param  c the comparator to determine the order of the list.  A
194      *        {@code null} value indicates that the elements' <i>natural
195      *        ordering</i> should be used.
196      * @throws ClassCastException if the list contains elements that are not
197      *         <i>mutually comparable</i> using the specified comparator.
198      * @throws UnsupportedOperationException if the specified list's
199      *         list-iterator does not support the {@code set} operation.
200      * @throws IllegalArgumentException (optional) if the comparator is
201      *         found to violate the {@link Comparator} contract
202      * @see List#sort(Comparator)
203      */
204     @SuppressWarnings({"unchecked", "rawtypes"})
sort(List<T> list, Comparator<? super T> c)205     public static <T> void sort(List<T> list, Comparator<? super T> c) {
206         // BEGIN Android-changed: List.sort() vs. Collections.sort() app compat.
207         // list.sort(c);
208         int targetSdkVersion = VMRuntime.getRuntime().getTargetSdkVersion();
209         if (targetSdkVersion > 25) {
210             list.sort(c);
211         } else {
212             // Compatibility behavior for API <= 25. http://b/33482884
213             if (list.getClass() == ArrayList.class) {
214                 Arrays.sort((T[]) ((ArrayList) list).elementData, 0, list.size(), c);
215                 return;
216             }
217 
218             Object[] a = list.toArray();
219             Arrays.sort(a, (Comparator) c);
220             ListIterator<T> i = list.listIterator();
221             for (int j = 0; j < a.length; j++) {
222                 i.next();
223                 i.set((T) a[j]);
224             }
225         }
226         // END Android-changed: List.sort() vs. Collections.sort() app compat.
227     }
228 
229 
230     /**
231      * Searches the specified list for the specified object using the binary
232      * search algorithm.  The list must be sorted into ascending order
233      * according to the {@linkplain Comparable natural ordering} of its
234      * elements (as by the {@link #sort(List)} method) prior to making this
235      * call.  If it is not sorted, the results are undefined.  If the list
236      * contains multiple elements equal to the specified object, there is no
237      * guarantee which one will be found.
238      *
239      * <p>This method runs in log(n) time for a "random access" list (which
240      * provides near-constant-time positional access).  If the specified list
241      * does not implement the {@link RandomAccess} interface and is large,
242      * this method will do an iterator-based binary search that performs
243      * O(n) link traversals and O(log n) element comparisons.
244      *
245      * @param  <T> the class of the objects in the list
246      * @param  list the list to be searched.
247      * @param  key the key to be searched for.
248      * @return the index of the search key, if it is contained in the list;
249      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
250      *         <i>insertion point</i> is defined as the point at which the
251      *         key would be inserted into the list: the index of the first
252      *         element greater than the key, or {@code list.size()} if all
253      *         elements in the list are less than the specified key.  Note
254      *         that this guarantees that the return value will be &gt;= 0 if
255      *         and only if the key is found.
256      * @throws ClassCastException if the list contains elements that are not
257      *         <i>mutually comparable</i> (for example, strings and
258      *         integers), or the search key is not mutually comparable
259      *         with the elements of the list.
260      */
261     public static <T>
binarySearch(List<? extends Comparable<? super T>> list, T key)262     int binarySearch(List<? extends Comparable<? super T>> list, T key) {
263         if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
264             return Collections.indexedBinarySearch(list, key);
265         else
266             return Collections.iteratorBinarySearch(list, key);
267     }
268 
269     private static <T>
indexedBinarySearch(List<? extends Comparable<? super T>> list, T key)270     int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) {
271         int low = 0;
272         int high = list.size()-1;
273 
274         while (low <= high) {
275             int mid = (low + high) >>> 1;
276             Comparable<? super T> midVal = list.get(mid);
277             int cmp = midVal.compareTo(key);
278 
279             if (cmp < 0)
280                 low = mid + 1;
281             else if (cmp > 0)
282                 high = mid - 1;
283             else
284                 return mid; // key found
285         }
286         return -(low + 1);  // key not found
287     }
288 
289     private static <T>
iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key)290     int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key)
291     {
292         int low = 0;
293         int high = list.size()-1;
294         ListIterator<? extends Comparable<? super T>> i = list.listIterator();
295 
296         while (low <= high) {
297             int mid = (low + high) >>> 1;
298             Comparable<? super T> midVal = get(i, mid);
299             int cmp = midVal.compareTo(key);
300 
301             if (cmp < 0)
302                 low = mid + 1;
303             else if (cmp > 0)
304                 high = mid - 1;
305             else
306                 return mid; // key found
307         }
308         return -(low + 1);  // key not found
309     }
310 
311     /**
312      * Gets the ith element from the given list by repositioning the specified
313      * list listIterator.
314      */
get(ListIterator<? extends T> i, int index)315     private static <T> T get(ListIterator<? extends T> i, int index) {
316         T obj = null;
317         int pos = i.nextIndex();
318         if (pos <= index) {
319             do {
320                 obj = i.next();
321             } while (pos++ < index);
322         } else {
323             do {
324                 obj = i.previous();
325             } while (--pos > index);
326         }
327         return obj;
328     }
329 
330     /**
331      * Searches the specified list for the specified object using the binary
332      * search algorithm.  The list must be sorted into ascending order
333      * according to the specified comparator (as by the
334      * {@link #sort(List, Comparator) sort(List, Comparator)}
335      * method), prior to making this call.  If it is
336      * not sorted, the results are undefined.  If the list contains multiple
337      * elements equal to the specified object, there is no guarantee which one
338      * will be found.
339      *
340      * <p>This method runs in log(n) time for a "random access" list (which
341      * provides near-constant-time positional access).  If the specified list
342      * does not implement the {@link RandomAccess} interface and is large,
343      * this method will do an iterator-based binary search that performs
344      * O(n) link traversals and O(log n) element comparisons.
345      *
346      * @param  <T> the class of the objects in the list
347      * @param  list the list to be searched.
348      * @param  key the key to be searched for.
349      * @param  c the comparator by which the list is ordered.
350      *         A {@code null} value indicates that the elements'
351      *         {@linkplain Comparable natural ordering} should be used.
352      * @return the index of the search key, if it is contained in the list;
353      *         otherwise, <code>(-(<i>insertion point</i>) - 1)</code>.  The
354      *         <i>insertion point</i> is defined as the point at which the
355      *         key would be inserted into the list: the index of the first
356      *         element greater than the key, or {@code list.size()} if all
357      *         elements in the list are less than the specified key.  Note
358      *         that this guarantees that the return value will be &gt;= 0 if
359      *         and only if the key is found.
360      * @throws ClassCastException if the list contains elements that are not
361      *         <i>mutually comparable</i> using the specified comparator,
362      *         or the search key is not mutually comparable with the
363      *         elements of the list using this comparator.
364      */
365     @SuppressWarnings("unchecked")
binarySearch(List<? extends T> list, T key, Comparator<? super T> c)366     public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {
367         if (c==null)
368             return binarySearch((List<? extends Comparable<? super T>>) list, key);
369 
370         if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
371             return Collections.indexedBinarySearch(list, key, c);
372         else
373             return Collections.iteratorBinarySearch(list, key, c);
374     }
375 
indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c)376     private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
377         int low = 0;
378         int high = l.size()-1;
379 
380         while (low <= high) {
381             int mid = (low + high) >>> 1;
382             T midVal = l.get(mid);
383             int cmp = c.compare(midVal, key);
384 
385             if (cmp < 0)
386                 low = mid + 1;
387             else if (cmp > 0)
388                 high = mid - 1;
389             else
390                 return mid; // key found
391         }
392         return -(low + 1);  // key not found
393     }
394 
iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c)395     private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) {
396         int low = 0;
397         int high = l.size()-1;
398         ListIterator<? extends T> i = l.listIterator();
399 
400         while (low <= high) {
401             int mid = (low + high) >>> 1;
402             T midVal = get(i, mid);
403             int cmp = c.compare(midVal, key);
404 
405             if (cmp < 0)
406                 low = mid + 1;
407             else if (cmp > 0)
408                 high = mid - 1;
409             else
410                 return mid; // key found
411         }
412         return -(low + 1);  // key not found
413     }
414 
415     /**
416      * Reverses the order of the elements in the specified list.<p>
417      *
418      * This method runs in linear time.
419      *
420      * @param  list the list whose elements are to be reversed.
421      * @throws UnsupportedOperationException if the specified list or
422      *         its list-iterator does not support the {@code set} operation.
423      */
424     @SuppressWarnings({"rawtypes", "unchecked"})
reverse(List<?> list)425     public static void reverse(List<?> list) {
426         int size = list.size();
427         if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
428             for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
429                 swap(list, i, j);
430         } else {
431             // instead of using a raw type here, it's possible to capture
432             // the wildcard but it will require a call to a supplementary
433             // private method
434             ListIterator fwd = list.listIterator();
435             ListIterator rev = list.listIterator(size);
436             for (int i=0, mid=list.size()>>1; i<mid; i++) {
437                 Object tmp = fwd.next();
438                 fwd.set(rev.previous());
439                 rev.set(tmp);
440             }
441         }
442     }
443 
444     /**
445      * Randomly permutes the specified list using a default source of
446      * randomness.  All permutations occur with approximately equal
447      * likelihood.
448      *
449      * <p>The hedge "approximately" is used in the foregoing description because
450      * default source of randomness is only approximately an unbiased source
451      * of independently chosen bits. If it were a perfect source of randomly
452      * chosen bits, then the algorithm would choose permutations with perfect
453      * uniformity.
454      *
455      * <p>This implementation traverses the list backwards, from the last
456      * element up to the second, repeatedly swapping a randomly selected element
457      * into the "current position".  Elements are randomly selected from the
458      * portion of the list that runs from the first element to the current
459      * position, inclusive.
460      *
461      * <p>This method runs in linear time.  If the specified list does not
462      * implement the {@link RandomAccess} interface and is large, this
463      * implementation dumps the specified list into an array before shuffling
464      * it, and dumps the shuffled array back into the list.  This avoids the
465      * quadratic behavior that would result from shuffling a "sequential
466      * access" list in place.
467      *
468      * @param  list the list to be shuffled.
469      * @throws UnsupportedOperationException if the specified list or
470      *         its list-iterator does not support the {@code set} operation.
471      */
shuffle(List<?> list)472     public static void shuffle(List<?> list) {
473         Random rnd = r;
474         if (rnd == null)
475             r = rnd = new Random(); // harmless race.
476         shuffle(list, rnd);
477     }
478 
479     private static Random r;
480 
481     /**
482      * Randomly permute the specified list using the specified source of
483      * randomness.  All permutations occur with equal likelihood
484      * assuming that the source of randomness is fair.<p>
485      *
486      * This implementation traverses the list backwards, from the last element
487      * up to the second, repeatedly swapping a randomly selected element into
488      * the "current position".  Elements are randomly selected from the
489      * portion of the list that runs from the first element to the current
490      * position, inclusive.<p>
491      *
492      * This method runs in linear time.  If the specified list does not
493      * implement the {@link RandomAccess} interface and is large, this
494      * implementation dumps the specified list into an array before shuffling
495      * it, and dumps the shuffled array back into the list.  This avoids the
496      * quadratic behavior that would result from shuffling a "sequential
497      * access" list in place.
498      *
499      * @param  list the list to be shuffled.
500      * @param  rnd the source of randomness to use to shuffle the list.
501      * @throws UnsupportedOperationException if the specified list or its
502      *         list-iterator does not support the {@code set} operation.
503      */
504     @SuppressWarnings({"rawtypes", "unchecked"})
shuffle(List<?> list, Random rnd)505     public static void shuffle(List<?> list, Random rnd) {
506         int size = list.size();
507         if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
508             for (int i=size; i>1; i--)
509                 swap(list, i-1, rnd.nextInt(i));
510         } else {
511             Object[] arr = list.toArray();
512 
513             // Shuffle array
514             for (int i=size; i>1; i--)
515                 swap(arr, i-1, rnd.nextInt(i));
516 
517             // Dump array back into list
518             // instead of using a raw type here, it's possible to capture
519             // the wildcard but it will require a call to a supplementary
520             // private method
521             ListIterator it = list.listIterator();
522             for (Object e : arr) {
523                 it.next();
524                 it.set(e);
525             }
526         }
527     }
528 
529     /**
530      * Swaps the elements at the specified positions in the specified list.
531      * (If the specified positions are equal, invoking this method leaves
532      * the list unchanged.)
533      *
534      * @param list The list in which to swap elements.
535      * @param i the index of one element to be swapped.
536      * @param j the index of the other element to be swapped.
537      * @throws IndexOutOfBoundsException if either {@code i} or {@code j}
538      *         is out of range (i &lt; 0 || i &gt;= list.size()
539      *         || j &lt; 0 || j &gt;= list.size()).
540      * @since 1.4
541      */
542     @SuppressWarnings({"rawtypes", "unchecked"})
swap(List<?> list, int i, int j)543     public static void swap(List<?> list, int i, int j) {
544         // instead of using a raw type here, it's possible to capture
545         // the wildcard but it will require a call to a supplementary
546         // private method
547         final List l = list;
548         l.set(i, l.set(j, l.get(i)));
549     }
550 
551     /**
552      * Swaps the two specified elements in the specified array.
553      */
swap(Object[] arr, int i, int j)554     private static void swap(Object[] arr, int i, int j) {
555         Object tmp = arr[i];
556         arr[i] = arr[j];
557         arr[j] = tmp;
558     }
559 
560     /**
561      * Replaces all of the elements of the specified list with the specified
562      * element. <p>
563      *
564      * This method runs in linear time.
565      *
566      * @param  <T> the class of the objects in the list
567      * @param  list the list to be filled with the specified element.
568      * @param  obj The element with which to fill the specified list.
569      * @throws UnsupportedOperationException if the specified list or its
570      *         list-iterator does not support the {@code set} operation.
571      */
fill(List<? super T> list, T obj)572     public static <T> void fill(List<? super T> list, T obj) {
573         int size = list.size();
574 
575         if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
576             for (int i=0; i<size; i++)
577                 list.set(i, obj);
578         } else {
579             ListIterator<? super T> itr = list.listIterator();
580             for (int i=0; i<size; i++) {
581                 itr.next();
582                 itr.set(obj);
583             }
584         }
585     }
586 
587     /**
588      * Copies all of the elements from one list into another.  After the
589      * operation, the index of each copied element in the destination list
590      * will be identical to its index in the source list.  The destination
591      * list's size must be greater than or equal to the source list's size.
592      * If it is greater, the remaining elements in the destination list are
593      * unaffected. <p>
594      *
595      * This method runs in linear time.
596      *
597      * @param  <T> the class of the objects in the lists
598      * @param  dest The destination list.
599      * @param  src The source list.
600      * @throws IndexOutOfBoundsException if the destination list is too small
601      *         to contain the entire source List.
602      * @throws UnsupportedOperationException if the destination list's
603      *         list-iterator does not support the {@code set} operation.
604      */
copy(List<? super T> dest, List<? extends T> src)605     public static <T> void copy(List<? super T> dest, List<? extends T> src) {
606         int srcSize = src.size();
607         if (srcSize > dest.size())
608             throw new IndexOutOfBoundsException("Source does not fit in dest");
609 
610         if (srcSize < COPY_THRESHOLD ||
611             (src instanceof RandomAccess && dest instanceof RandomAccess)) {
612             for (int i=0; i<srcSize; i++)
613                 dest.set(i, src.get(i));
614         } else {
615             ListIterator<? super T> di=dest.listIterator();
616             ListIterator<? extends T> si=src.listIterator();
617             for (int i=0; i<srcSize; i++) {
618                 di.next();
619                 di.set(si.next());
620             }
621         }
622     }
623 
624     /**
625      * Returns the minimum element of the given collection, according to the
626      * <i>natural ordering</i> of its elements.  All elements in the
627      * collection must implement the {@code Comparable} interface.
628      * Furthermore, all elements in the collection must be <i>mutually
629      * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
630      * {@code ClassCastException} for any elements {@code e1} and
631      * {@code e2} in the collection).<p>
632      *
633      * This method iterates over the entire collection, hence it requires
634      * time proportional to the size of the collection.
635      *
636      * @param  <T> the class of the objects in the collection
637      * @param  coll the collection whose minimum element is to be determined.
638      * @return the minimum element of the given collection, according
639      *         to the <i>natural ordering</i> of its elements.
640      * @throws ClassCastException if the collection contains elements that are
641      *         not <i>mutually comparable</i> (for example, strings and
642      *         integers).
643      * @throws NoSuchElementException if the collection is empty.
644      * @see Comparable
645      */
min(Collection<? extends T> coll)646     public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
647         Iterator<? extends T> i = coll.iterator();
648         T candidate = i.next();
649 
650         while (i.hasNext()) {
651             T next = i.next();
652             if (next.compareTo(candidate) < 0)
653                 candidate = next;
654         }
655         return candidate;
656     }
657 
658     /**
659      * Returns the minimum element of the given collection, according to the
660      * order induced by the specified comparator.  All elements in the
661      * collection must be <i>mutually comparable</i> by the specified
662      * comparator (that is, {@code comp.compare(e1, e2)} must not throw a
663      * {@code ClassCastException} for any elements {@code e1} and
664      * {@code e2} in the collection).<p>
665      *
666      * This method iterates over the entire collection, hence it requires
667      * time proportional to the size of the collection.
668      *
669      * @param  <T> the class of the objects in the collection
670      * @param  coll the collection whose minimum element is to be determined.
671      * @param  comp the comparator with which to determine the minimum element.
672      *         A {@code null} value indicates that the elements' <i>natural
673      *         ordering</i> should be used.
674      * @return the minimum element of the given collection, according
675      *         to the specified comparator.
676      * @throws ClassCastException if the collection contains elements that are
677      *         not <i>mutually comparable</i> using the specified comparator.
678      * @throws NoSuchElementException if the collection is empty.
679      * @see Comparable
680      */
681     @SuppressWarnings({"unchecked", "rawtypes"})
min(Collection<? extends T> coll, Comparator<? super T> comp)682     public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
683         if (comp==null)
684             return (T)min((Collection) coll);
685 
686         Iterator<? extends T> i = coll.iterator();
687         T candidate = i.next();
688 
689         while (i.hasNext()) {
690             T next = i.next();
691             if (comp.compare(next, candidate) < 0)
692                 candidate = next;
693         }
694         return candidate;
695     }
696 
697     /**
698      * Returns the maximum element of the given collection, according to the
699      * <i>natural ordering</i> of its elements.  All elements in the
700      * collection must implement the {@code Comparable} interface.
701      * Furthermore, all elements in the collection must be <i>mutually
702      * comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
703      * {@code ClassCastException} for any elements {@code e1} and
704      * {@code e2} in the collection).<p>
705      *
706      * This method iterates over the entire collection, hence it requires
707      * time proportional to the size of the collection.
708      *
709      * @param  <T> the class of the objects in the collection
710      * @param  coll the collection whose maximum element is to be determined.
711      * @return the maximum element of the given collection, according
712      *         to the <i>natural ordering</i> of its elements.
713      * @throws ClassCastException if the collection contains elements that are
714      *         not <i>mutually comparable</i> (for example, strings and
715      *         integers).
716      * @throws NoSuchElementException if the collection is empty.
717      * @see Comparable
718      */
max(Collection<? extends T> coll)719     public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
720         Iterator<? extends T> i = coll.iterator();
721         T candidate = i.next();
722 
723         while (i.hasNext()) {
724             T next = i.next();
725             if (next.compareTo(candidate) > 0)
726                 candidate = next;
727         }
728         return candidate;
729     }
730 
731     /**
732      * Returns the maximum element of the given collection, according to the
733      * order induced by the specified comparator.  All elements in the
734      * collection must be <i>mutually comparable</i> by the specified
735      * comparator (that is, {@code comp.compare(e1, e2)} must not throw a
736      * {@code ClassCastException} for any elements {@code e1} and
737      * {@code e2} in the collection).<p>
738      *
739      * This method iterates over the entire collection, hence it requires
740      * time proportional to the size of the collection.
741      *
742      * @param  <T> the class of the objects in the collection
743      * @param  coll the collection whose maximum element is to be determined.
744      * @param  comp the comparator with which to determine the maximum element.
745      *         A {@code null} value indicates that the elements' <i>natural
746      *        ordering</i> should be used.
747      * @return the maximum element of the given collection, according
748      *         to the specified comparator.
749      * @throws ClassCastException if the collection contains elements that are
750      *         not <i>mutually comparable</i> using the specified comparator.
751      * @throws NoSuchElementException if the collection is empty.
752      * @see Comparable
753      */
754     @SuppressWarnings({"unchecked", "rawtypes"})
max(Collection<? extends T> coll, Comparator<? super T> comp)755     public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
756         if (comp==null)
757             return (T)max((Collection) coll);
758 
759         Iterator<? extends T> i = coll.iterator();
760         T candidate = i.next();
761 
762         while (i.hasNext()) {
763             T next = i.next();
764             if (comp.compare(next, candidate) > 0)
765                 candidate = next;
766         }
767         return candidate;
768     }
769 
770     /**
771      * Rotates the elements in the specified list by the specified distance.
772      * After calling this method, the element at index {@code i} will be
773      * the element previously at index {@code (i - distance)} mod
774      * {@code list.size()}, for all values of {@code i} between {@code 0}
775      * and {@code list.size()-1}, inclusive.  (This method has no effect on
776      * the size of the list.)
777      *
778      * <p>For example, suppose {@code list} comprises{@code  [t, a, n, k, s]}.
779      * After invoking {@code Collections.rotate(list, 1)} (or
780      * {@code Collections.rotate(list, -4)}), {@code list} will comprise
781      * {@code [s, t, a, n, k]}.
782      *
783      * <p>Note that this method can usefully be applied to sublists to
784      * move one or more elements within a list while preserving the
785      * order of the remaining elements.  For example, the following idiom
786      * moves the element at index {@code j} forward to position
787      * {@code k} (which must be greater than or equal to {@code j}):
788      * <pre>
789      *     Collections.rotate(list.subList(j, k+1), -1);
790      * </pre>
791      * To make this concrete, suppose {@code list} comprises
792      * {@code [a, b, c, d, e]}.  To move the element at index {@code 1}
793      * ({@code b}) forward two positions, perform the following invocation:
794      * <pre>
795      *     Collections.rotate(l.subList(1, 4), -1);
796      * </pre>
797      * The resulting list is {@code [a, c, d, b, e]}.
798      *
799      * <p>To move more than one element forward, increase the absolute value
800      * of the rotation distance.  To move elements backward, use a positive
801      * shift distance.
802      *
803      * <p>If the specified list is small or implements the {@link
804      * RandomAccess} interface, this implementation exchanges the first
805      * element into the location it should go, and then repeatedly exchanges
806      * the displaced element into the location it should go until a displaced
807      * element is swapped into the first element.  If necessary, the process
808      * is repeated on the second and successive elements, until the rotation
809      * is complete.  If the specified list is large and doesn't implement the
810      * {@code RandomAccess} interface, this implementation breaks the
811      * list into two sublist views around index {@code -distance mod size}.
812      * Then the {@link #reverse(List)} method is invoked on each sublist view,
813      * and finally it is invoked on the entire list.  For a more complete
814      * description of both algorithms, see Section 2.3 of Jon Bentley's
815      * <i>Programming Pearls</i> (Addison-Wesley, 1986).
816      *
817      * @param list the list to be rotated.
818      * @param distance the distance to rotate the list.  There are no
819      *        constraints on this value; it may be zero, negative, or
820      *        greater than {@code list.size()}.
821      * @throws UnsupportedOperationException if the specified list or
822      *         its list-iterator does not support the {@code set} operation.
823      * @since 1.4
824      */
rotate(List<?> list, int distance)825     public static void rotate(List<?> list, int distance) {
826         if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
827             rotate1(list, distance);
828         else
829             rotate2(list, distance);
830     }
831 
rotate1(List<T> list, int distance)832     private static <T> void rotate1(List<T> list, int distance) {
833         int size = list.size();
834         if (size == 0)
835             return;
836         distance = distance % size;
837         if (distance < 0)
838             distance += size;
839         if (distance == 0)
840             return;
841 
842         for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
843             T displaced = list.get(cycleStart);
844             int i = cycleStart;
845             do {
846                 i += distance;
847                 if (i >= size)
848                     i -= size;
849                 displaced = list.set(i, displaced);
850                 nMoved ++;
851             } while (i != cycleStart);
852         }
853     }
854 
rotate2(List<?> list, int distance)855     private static void rotate2(List<?> list, int distance) {
856         int size = list.size();
857         if (size == 0)
858             return;
859         int mid =  -distance % size;
860         if (mid < 0)
861             mid += size;
862         if (mid == 0)
863             return;
864 
865         reverse(list.subList(0, mid));
866         reverse(list.subList(mid, size));
867         reverse(list);
868     }
869 
870     /**
871      * Replaces all occurrences of one specified value in a list with another.
872      * More formally, replaces with {@code newVal} each element {@code e}
873      * in {@code list} such that
874      * {@code (oldVal==null ? e==null : oldVal.equals(e))}.
875      * (This method has no effect on the size of the list.)
876      *
877      * @param  <T> the class of the objects in the list
878      * @param list the list in which replacement is to occur.
879      * @param oldVal the old value to be replaced.
880      * @param newVal the new value with which {@code oldVal} is to be
881      *        replaced.
882      * @return {@code true} if {@code list} contained one or more elements
883      *         {@code e} such that
884      *         {@code (oldVal==null ?  e==null : oldVal.equals(e))}.
885      * @throws UnsupportedOperationException if the specified list or
886      *         its list-iterator does not support the {@code set} operation.
887      * @since  1.4
888      */
replaceAll(List<T> list, T oldVal, T newVal)889     public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {
890         boolean result = false;
891         int size = list.size();
892         if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
893             if (oldVal==null) {
894                 for (int i=0; i<size; i++) {
895                     if (list.get(i)==null) {
896                         list.set(i, newVal);
897                         result = true;
898                     }
899                 }
900             } else {
901                 for (int i=0; i<size; i++) {
902                     if (oldVal.equals(list.get(i))) {
903                         list.set(i, newVal);
904                         result = true;
905                     }
906                 }
907             }
908         } else {
909             ListIterator<T> itr=list.listIterator();
910             if (oldVal==null) {
911                 for (int i=0; i<size; i++) {
912                     if (itr.next()==null) {
913                         itr.set(newVal);
914                         result = true;
915                     }
916                 }
917             } else {
918                 for (int i=0; i<size; i++) {
919                     if (oldVal.equals(itr.next())) {
920                         itr.set(newVal);
921                         result = true;
922                     }
923                 }
924             }
925         }
926         return result;
927     }
928 
929     /**
930      * Returns the starting position of the first occurrence of the specified
931      * target list within the specified source list, or -1 if there is no
932      * such occurrence.  More formally, returns the lowest index {@code i}
933      * such that {@code source.subList(i, i+target.size()).equals(target)},
934      * or -1 if there is no such index.  (Returns -1 if
935      * {@code target.size() > source.size()})
936      *
937      * <p>This implementation uses the "brute force" technique of scanning
938      * over the source list, looking for a match with the target at each
939      * location in turn.
940      *
941      * @param source the list in which to search for the first occurrence
942      *        of {@code target}.
943      * @param target the list to search for as a subList of {@code source}.
944      * @return the starting position of the first occurrence of the specified
945      *         target list within the specified source list, or -1 if there
946      *         is no such occurrence.
947      * @since  1.4
948      */
indexOfSubList(List<?> source, List<?> target)949     public static int indexOfSubList(List<?> source, List<?> target) {
950         int sourceSize = source.size();
951         int targetSize = target.size();
952         int maxCandidate = sourceSize - targetSize;
953 
954         if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
955             (source instanceof RandomAccess&&target instanceof RandomAccess)) {
956         nextCand:
957             for (int candidate = 0; candidate <= maxCandidate; candidate++) {
958                 for (int i=0, j=candidate; i<targetSize; i++, j++)
959                     if (!eq(target.get(i), source.get(j)))
960                         continue nextCand;  // Element mismatch, try next cand
961                 return candidate;  // All elements of candidate matched target
962             }
963         } else {  // Iterator version of above algorithm
964             ListIterator<?> si = source.listIterator();
965         nextCand:
966             for (int candidate = 0; candidate <= maxCandidate; candidate++) {
967                 ListIterator<?> ti = target.listIterator();
968                 for (int i=0; i<targetSize; i++) {
969                     if (!eq(ti.next(), si.next())) {
970                         // Back up source iterator to next candidate
971                         for (int j=0; j<i; j++)
972                             si.previous();
973                         continue nextCand;
974                     }
975                 }
976                 return candidate;
977             }
978         }
979         return -1;  // No candidate matched the target
980     }
981 
982     /**
983      * Returns the starting position of the last occurrence of the specified
984      * target list within the specified source list, or -1 if there is no such
985      * occurrence.  More formally, returns the highest index {@code i}
986      * such that {@code source.subList(i, i+target.size()).equals(target)},
987      * or -1 if there is no such index.  (Returns -1 if
988      * {@code target.size() > source.size()})
989      *
990      * <p>This implementation uses the "brute force" technique of iterating
991      * over the source list, looking for a match with the target at each
992      * location in turn.
993      *
994      * @param source the list in which to search for the last occurrence
995      *        of {@code target}.
996      * @param target the list to search for as a subList of {@code source}.
997      * @return the starting position of the last occurrence of the specified
998      *         target list within the specified source list, or -1 if there
999      *         is no such occurrence.
1000      * @since  1.4
1001      */
lastIndexOfSubList(List<?> source, List<?> target)1002     public static int lastIndexOfSubList(List<?> source, List<?> target) {
1003         int sourceSize = source.size();
1004         int targetSize = target.size();
1005         int maxCandidate = sourceSize - targetSize;
1006 
1007         if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
1008             source instanceof RandomAccess) {   // Index access version
1009         nextCand:
1010             for (int candidate = maxCandidate; candidate >= 0; candidate--) {
1011                 for (int i=0, j=candidate; i<targetSize; i++, j++)
1012                     if (!eq(target.get(i), source.get(j)))
1013                         continue nextCand;  // Element mismatch, try next cand
1014                 return candidate;  // All elements of candidate matched target
1015             }
1016         } else {  // Iterator version of above algorithm
1017             if (maxCandidate < 0)
1018                 return -1;
1019             ListIterator<?> si = source.listIterator(maxCandidate);
1020         nextCand:
1021             for (int candidate = maxCandidate; candidate >= 0; candidate--) {
1022                 ListIterator<?> ti = target.listIterator();
1023                 for (int i=0; i<targetSize; i++) {
1024                     if (!eq(ti.next(), si.next())) {
1025                         if (candidate != 0) {
1026                             // Back up source iterator to next candidate
1027                             for (int j=0; j<=i+1; j++)
1028                                 si.previous();
1029                         }
1030                         continue nextCand;
1031                     }
1032                 }
1033                 return candidate;
1034             }
1035         }
1036         return -1;  // No candidate matched the target
1037     }
1038 
1039 
1040     // Unmodifiable Wrappers
1041 
1042     /**
1043      * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1044      * specified collection. Query operations on the returned collection "read through"
1045      * to the specified collection, and attempts to modify the returned
1046      * collection, whether direct or via its iterator, result in an
1047      * {@code UnsupportedOperationException}.<p>
1048      *
1049      * The returned collection does <i>not</i> pass the hashCode and equals
1050      * operations through to the backing collection, but relies on
1051      * {@code Object}'s {@code equals} and {@code hashCode} methods.  This
1052      * is necessary to preserve the contracts of these operations in the case
1053      * that the backing collection is a set or a list.<p>
1054      *
1055      * The returned collection will be serializable if the specified collection
1056      * is serializable.
1057      *
1058      * @implNote This method may return its argument if the argument is already unmodifiable.
1059      * @param  <T> the class of the objects in the collection
1060      * @param  c the collection for which an unmodifiable view is to be
1061      *         returned.
1062      * @return an unmodifiable view of the specified collection.
1063      */
1064     @SuppressWarnings("unchecked")
unmodifiableCollection(Collection<? extends T> c)1065     public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
1066         if (c.getClass() == UnmodifiableCollection.class) {
1067             return (Collection<T>) c;
1068         }
1069         return new UnmodifiableCollection<>(c);
1070     }
1071 
1072     /**
1073      * @serial include
1074      */
1075     static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
1076         @java.io.Serial
1077         private static final long serialVersionUID = 1820017752578914078L;
1078 
1079         @SuppressWarnings("serial") // Conditionally serializable
1080         final Collection<? extends E> c;
1081 
UnmodifiableCollection(Collection<? extends E> c)1082         UnmodifiableCollection(Collection<? extends E> c) {
1083             if (c==null)
1084                 throw new NullPointerException();
1085             this.c = c;
1086         }
1087 
size()1088         public int size()                          {return c.size();}
isEmpty()1089         public boolean isEmpty()                   {return c.isEmpty();}
contains(Object o)1090         public boolean contains(Object o)          {return c.contains(o);}
toArray()1091         public Object[] toArray()                  {return c.toArray();}
toArray(T[] a)1092         public <T> T[] toArray(T[] a)              {return c.toArray(a);}
toArray(IntFunction<T[]> f)1093         public <T> T[] toArray(IntFunction<T[]> f) {return c.toArray(f);}
toString()1094         public String toString()                   {return c.toString();}
1095 
iterator()1096         public Iterator<E> iterator() {
1097             return new Iterator<E>() {
1098                 private final Iterator<? extends E> i = c.iterator();
1099 
1100                 public boolean hasNext() {return i.hasNext();}
1101                 public E next()          {return i.next();}
1102                 public void remove() {
1103                     throw new UnsupportedOperationException();
1104                 }
1105                 @Override
1106                 public void forEachRemaining(Consumer<? super E> action) {
1107                     // Use backing collection version
1108                     i.forEachRemaining(action);
1109                 }
1110             };
1111         }
1112 
add(E e)1113         public boolean add(E e) {
1114             throw new UnsupportedOperationException();
1115         }
remove(Object o)1116         public boolean remove(Object o) {
1117             throw new UnsupportedOperationException();
1118         }
1119 
containsAll(Collection<?> coll)1120         public boolean containsAll(Collection<?> coll) {
1121             return c.containsAll(coll);
1122         }
addAll(Collection<? extends E> coll)1123         public boolean addAll(Collection<? extends E> coll) {
1124             throw new UnsupportedOperationException();
1125         }
removeAll(Collection<?> coll)1126         public boolean removeAll(Collection<?> coll) {
1127             throw new UnsupportedOperationException();
1128         }
retainAll(Collection<?> coll)1129         public boolean retainAll(Collection<?> coll) {
1130             throw new UnsupportedOperationException();
1131         }
clear()1132         public void clear() {
1133             throw new UnsupportedOperationException();
1134         }
1135 
1136         // Override default methods in Collection
1137         @Override
forEach(Consumer<? super E> action)1138         public void forEach(Consumer<? super E> action) {
1139             c.forEach(action);
1140         }
1141         @Override
removeIf(Predicate<? super E> filter)1142         public boolean removeIf(Predicate<? super E> filter) {
1143             throw new UnsupportedOperationException();
1144         }
1145         @SuppressWarnings("unchecked")
1146         @Override
spliterator()1147         public Spliterator<E> spliterator() {
1148             return (Spliterator<E>)c.spliterator();
1149         }
1150         @SuppressWarnings("unchecked")
1151         @Override
stream()1152         public Stream<E> stream() {
1153             return (Stream<E>)c.stream();
1154         }
1155         @SuppressWarnings("unchecked")
1156         @Override
parallelStream()1157         public Stream<E> parallelStream() {
1158             return (Stream<E>)c.parallelStream();
1159         }
1160     }
1161 
1162     /**
1163      * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1164      * specified set. Query operations on the returned set "read through" to the specified
1165      * set, and attempts to modify the returned set, whether direct or via its
1166      * iterator, result in an {@code UnsupportedOperationException}.<p>
1167      *
1168      * The returned set will be serializable if the specified set
1169      * is serializable.
1170      *
1171      * @implNote This method may return its argument if the argument is already unmodifiable.
1172      * @param  <T> the class of the objects in the set
1173      * @param  s the set for which an unmodifiable view is to be returned.
1174      * @return an unmodifiable view of the specified set.
1175      */
1176     @SuppressWarnings("unchecked")
unmodifiableSet(Set<? extends T> s)1177     public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1178         // Not checking for subclasses because of heap pollution and information leakage.
1179         if (s.getClass() == UnmodifiableSet.class) {
1180             return (Set<T>) s;
1181         }
1182         return new UnmodifiableSet<>(s);
1183     }
1184 
1185     /**
1186      * @serial include
1187      */
1188     static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1189                                  implements Set<E>, Serializable {
1190         @java.io.Serial
1191         private static final long serialVersionUID = -9215047833775013803L;
1192 
UnmodifiableSet(Set<? extends E> s)1193         UnmodifiableSet(Set<? extends E> s)     {super(s);}
equals(Object o)1194         public boolean equals(Object o) {return o == this || c.equals(o);}
hashCode()1195         public int hashCode()           {return c.hashCode();}
1196     }
1197 
1198     /**
1199      * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1200      * specified sorted set. Query operations on the returned sorted set "read
1201      * through" to the specified sorted set.  Attempts to modify the returned
1202      * sorted set, whether direct, via its iterator, or via its
1203      * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
1204      * an {@code UnsupportedOperationException}.<p>
1205      *
1206      * The returned sorted set will be serializable if the specified sorted set
1207      * is serializable.
1208      *
1209      * @implNote This method may return its argument if the argument is already unmodifiable.
1210      * @param  <T> the class of the objects in the set
1211      * @param s the sorted set for which an unmodifiable view is to be
1212      *        returned.
1213      * @return an unmodifiable view of the specified sorted set.
1214      */
unmodifiableSortedSet(SortedSet<T> s)1215     public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1216         // Not checking for subclasses because of heap pollution and information leakage.
1217         if (s.getClass() == UnmodifiableSortedSet.class) {
1218             return s;
1219         }
1220         return new UnmodifiableSortedSet<>(s);
1221     }
1222 
1223     /**
1224      * @serial include
1225      */
1226     static class UnmodifiableSortedSet<E>
1227                              extends UnmodifiableSet<E>
1228                              implements SortedSet<E>, Serializable {
1229         @java.io.Serial
1230         private static final long serialVersionUID = -4929149591599911165L;
1231         @SuppressWarnings("serial") // Conditionally serializable
1232         private final SortedSet<E> ss;
1233 
UnmodifiableSortedSet(SortedSet<E> s)1234         UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1235 
comparator()1236         public Comparator<? super E> comparator() {return ss.comparator();}
1237 
subSet(E fromElement, E toElement)1238         public SortedSet<E> subSet(E fromElement, E toElement) {
1239             return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
1240         }
headSet(E toElement)1241         public SortedSet<E> headSet(E toElement) {
1242             return new UnmodifiableSortedSet<>(ss.headSet(toElement));
1243         }
tailSet(E fromElement)1244         public SortedSet<E> tailSet(E fromElement) {
1245             return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
1246         }
1247 
first()1248         public E first()                   {return ss.first();}
last()1249         public E last()                    {return ss.last();}
1250     }
1251 
1252     /**
1253      * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1254      * specified navigable set. Query operations on the returned navigable set "read
1255      * through" to the specified navigable set.  Attempts to modify the returned
1256      * navigable set, whether direct, via its iterator, or via its
1257      * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
1258      * an {@code UnsupportedOperationException}.<p>
1259      *
1260      * The returned navigable set will be serializable if the specified
1261      * navigable set is serializable.
1262      *
1263      * @implNote This method may return its argument if the argument is already unmodifiable.
1264      * @param  <T> the class of the objects in the set
1265      * @param s the navigable set for which an unmodifiable view is to be
1266      *        returned
1267      * @return an unmodifiable view of the specified navigable set
1268      * @since 1.8
1269      */
unmodifiableNavigableSet(NavigableSet<T> s)1270     public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) {
1271         if (s.getClass() == UnmodifiableNavigableSet.class) {
1272             return s;
1273         }
1274         return new UnmodifiableNavigableSet<>(s);
1275     }
1276 
1277     /**
1278      * Wraps a navigable set and disables all of the mutative operations.
1279      *
1280      * @param <E> type of elements
1281      * @serial include
1282      */
1283     static class UnmodifiableNavigableSet<E>
1284                              extends UnmodifiableSortedSet<E>
1285                              implements NavigableSet<E>, Serializable {
1286 
1287         @java.io.Serial
1288         private static final long serialVersionUID = -6027448201786391929L;
1289 
1290         /**
1291          * A singleton empty unmodifiable navigable set used for
1292          * {@link #emptyNavigableSet()}.
1293          *
1294          * @param <E> type of elements, if there were any, and bounds
1295          */
1296         private static class EmptyNavigableSet<E> extends UnmodifiableNavigableSet<E>
1297             implements Serializable {
1298             @java.io.Serial
1299             private static final long serialVersionUID = -6291252904449939134L;
1300 
EmptyNavigableSet()1301             public EmptyNavigableSet() {
1302                 super(new TreeSet<>());
1303             }
1304 
1305             @java.io.Serial
readResolve()1306             private Object readResolve()        { return EMPTY_NAVIGABLE_SET; }
1307         }
1308 
1309         @SuppressWarnings("rawtypes")
1310         private static final NavigableSet<?> EMPTY_NAVIGABLE_SET =
1311                 new EmptyNavigableSet<>();
1312 
1313         /**
1314          * The instance we are protecting.
1315          */
1316         @SuppressWarnings("serial") // Conditionally serializable
1317         private final NavigableSet<E> ns;
1318 
UnmodifiableNavigableSet(NavigableSet<E> s)1319         UnmodifiableNavigableSet(NavigableSet<E> s)         {super(s); ns = s;}
1320 
lower(E e)1321         public E lower(E e)                             { return ns.lower(e); }
floor(E e)1322         public E floor(E e)                             { return ns.floor(e); }
ceiling(E e)1323         public E ceiling(E e)                         { return ns.ceiling(e); }
higher(E e)1324         public E higher(E e)                           { return ns.higher(e); }
pollFirst()1325         public E pollFirst()     { throw new UnsupportedOperationException(); }
pollLast()1326         public E pollLast()      { throw new UnsupportedOperationException(); }
descendingSet()1327         public NavigableSet<E> descendingSet()
1328                  { return new UnmodifiableNavigableSet<>(ns.descendingSet()); }
descendingIterator()1329         public Iterator<E> descendingIterator()
1330                                          { return descendingSet().iterator(); }
1331 
subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)1332         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
1333             return new UnmodifiableNavigableSet<>(
1334                 ns.subSet(fromElement, fromInclusive, toElement, toInclusive));
1335         }
1336 
headSet(E toElement, boolean inclusive)1337         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
1338             return new UnmodifiableNavigableSet<>(
1339                 ns.headSet(toElement, inclusive));
1340         }
1341 
tailSet(E fromElement, boolean inclusive)1342         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
1343             return new UnmodifiableNavigableSet<>(
1344                 ns.tailSet(fromElement, inclusive));
1345         }
1346     }
1347 
1348     /**
1349      * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1350      * specified list. Query operations on the returned list "read through" to the
1351      * specified list, and attempts to modify the returned list, whether
1352      * direct or via its iterator, result in an
1353      * {@code UnsupportedOperationException}.<p>
1354      *
1355      * The returned list will be serializable if the specified list
1356      * is serializable. Similarly, the returned list will implement
1357      * {@link RandomAccess} if the specified list does.
1358      *
1359      * @implNote This method may return its argument if the argument is already unmodifiable.
1360      * @param  <T> the class of the objects in the list
1361      * @param  list the list for which an unmodifiable view is to be returned.
1362      * @return an unmodifiable view of the specified list.
1363      */
1364     @SuppressWarnings("unchecked")
unmodifiableList(List<? extends T> list)1365     public static <T> List<T> unmodifiableList(List<? extends T> list) {
1366         if (list.getClass() == UnmodifiableList.class || list.getClass() == UnmodifiableRandomAccessList.class) {
1367            return (List<T>) list;
1368         }
1369 
1370         return (list instanceof RandomAccess ?
1371                 new UnmodifiableRandomAccessList<>(list) :
1372                 new UnmodifiableList<>(list));
1373     }
1374 
1375     /**
1376      * @serial include
1377      */
1378     static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1379                                   implements List<E> {
1380         @java.io.Serial
1381         private static final long serialVersionUID = -283967356065247728L;
1382 
1383         @SuppressWarnings("serial") // Conditionally serializable
1384         final List<? extends E> list;
1385 
UnmodifiableList(List<? extends E> list)1386         UnmodifiableList(List<? extends E> list) {
1387             super(list);
1388             this.list = list;
1389         }
1390 
equals(Object o)1391         public boolean equals(Object o) {return o == this || list.equals(o);}
hashCode()1392         public int hashCode()           {return list.hashCode();}
1393 
get(int index)1394         public E get(int index) {return list.get(index);}
set(int index, E element)1395         public E set(int index, E element) {
1396             throw new UnsupportedOperationException();
1397         }
add(int index, E element)1398         public void add(int index, E element) {
1399             throw new UnsupportedOperationException();
1400         }
remove(int index)1401         public E remove(int index) {
1402             throw new UnsupportedOperationException();
1403         }
indexOf(Object o)1404         public int indexOf(Object o)            {return list.indexOf(o);}
lastIndexOf(Object o)1405         public int lastIndexOf(Object o)        {return list.lastIndexOf(o);}
addAll(int index, Collection<? extends E> c)1406         public boolean addAll(int index, Collection<? extends E> c) {
1407             throw new UnsupportedOperationException();
1408         }
1409 
1410         @Override
replaceAll(UnaryOperator<E> operator)1411         public void replaceAll(UnaryOperator<E> operator) {
1412             throw new UnsupportedOperationException();
1413         }
1414         @Override
sort(Comparator<? super E> c)1415         public void sort(Comparator<? super E> c) {
1416             throw new UnsupportedOperationException();
1417         }
1418 
listIterator()1419         public ListIterator<E> listIterator()   {return listIterator(0);}
1420 
listIterator(final int index)1421         public ListIterator<E> listIterator(final int index) {
1422             return new ListIterator<E>() {
1423                 private final ListIterator<? extends E> i
1424                     = list.listIterator(index);
1425 
1426                 public boolean hasNext()     {return i.hasNext();}
1427                 public E next()              {return i.next();}
1428                 public boolean hasPrevious() {return i.hasPrevious();}
1429                 public E previous()          {return i.previous();}
1430                 public int nextIndex()       {return i.nextIndex();}
1431                 public int previousIndex()   {return i.previousIndex();}
1432 
1433                 public void remove() {
1434                     throw new UnsupportedOperationException();
1435                 }
1436                 public void set(E e) {
1437                     throw new UnsupportedOperationException();
1438                 }
1439                 public void add(E e) {
1440                     throw new UnsupportedOperationException();
1441                 }
1442 
1443                 @Override
1444                 public void forEachRemaining(Consumer<? super E> action) {
1445                     i.forEachRemaining(action);
1446                 }
1447             };
1448         }
1449 
subList(int fromIndex, int toIndex)1450         public List<E> subList(int fromIndex, int toIndex) {
1451             return new UnmodifiableList<>(list.subList(fromIndex, toIndex));
1452         }
1453 
1454         /**
1455          * UnmodifiableRandomAccessList instances are serialized as
1456          * UnmodifiableList instances to allow them to be deserialized
1457          * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
1458          * This method inverts the transformation.  As a beneficial
1459          * side-effect, it also grafts the RandomAccess marker onto
1460          * UnmodifiableList instances that were serialized in pre-1.4 JREs.
1461          *
1462          * Note: Unfortunately, UnmodifiableRandomAccessList instances
1463          * serialized in 1.4.1 and deserialized in 1.4 will become
1464          * UnmodifiableList instances, as this method was missing in 1.4.
1465          */
1466         @java.io.Serial
readResolve()1467         private Object readResolve() {
1468             return (list instanceof RandomAccess
1469                     ? new UnmodifiableRandomAccessList<>(list)
1470                     : this);
1471         }
1472     }
1473 
1474     /**
1475      * @serial include
1476      */
1477     static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
1478                                               implements RandomAccess
1479     {
1480         UnmodifiableRandomAccessList(List<? extends E> list) {
1481             super(list);
1482         }
1483 
1484         public List<E> subList(int fromIndex, int toIndex) {
1485             return new UnmodifiableRandomAccessList<>(
1486                 list.subList(fromIndex, toIndex));
1487         }
1488 
1489         @java.io.Serial
1490         private static final long serialVersionUID = -2542308836966382001L;
1491 
1492         /**
1493          * Allows instances to be deserialized in pre-1.4 JREs (which do
1494          * not have UnmodifiableRandomAccessList).  UnmodifiableList has
1495          * a readResolve method that inverts this transformation upon
1496          * deserialization.
1497          */
1498         @java.io.Serial
1499         private Object writeReplace() {
1500             return new UnmodifiableList<>(list);
1501         }
1502     }
1503 
1504     /**
1505      * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1506      * specified map. Query operations on the returned map "read through"
1507      * to the specified map, and attempts to modify the returned
1508      * map, whether direct or via its collection views, result in an
1509      * {@code UnsupportedOperationException}.<p>
1510      *
1511      * The returned map will be serializable if the specified map
1512      * is serializable.
1513      *
1514      * @implNote This method may return its argument if the argument is already unmodifiable.
1515      * @param <K> the class of the map keys
1516      * @param <V> the class of the map values
1517      * @param  m the map for which an unmodifiable view is to be returned.
1518      * @return an unmodifiable view of the specified map.
1519      */
1520     @SuppressWarnings("unchecked")
1521     public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1522         // Not checking for subclasses because of heap pollution and information leakage.
1523         if (m.getClass() == UnmodifiableMap.class) {
1524             return (Map<K,V>) m;
1525         }
1526         return new UnmodifiableMap<>(m);
1527     }
1528 
1529     /**
1530      * @serial include
1531      */
1532     private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1533         @java.io.Serial
1534         private static final long serialVersionUID = -1034234728574286014L;
1535 
1536         @SuppressWarnings("serial") // Conditionally serializable
1537         private final Map<? extends K, ? extends V> m;
1538 
1539         UnmodifiableMap(Map<? extends K, ? extends V> m) {
1540             if (m==null)
1541                 throw new NullPointerException();
1542             this.m = m;
1543         }
1544 
1545         public int size()                        {return m.size();}
1546         public boolean isEmpty()                 {return m.isEmpty();}
1547         public boolean containsKey(Object key)   {return m.containsKey(key);}
1548         public boolean containsValue(Object val) {return m.containsValue(val);}
1549         public V get(Object key)                 {return m.get(key);}
1550 
1551         public V put(K key, V value) {
1552             throw new UnsupportedOperationException();
1553         }
1554         public V remove(Object key) {
1555             throw new UnsupportedOperationException();
1556         }
1557         public void putAll(Map<? extends K, ? extends V> m) {
1558             throw new UnsupportedOperationException();
1559         }
1560         public void clear() {
1561             throw new UnsupportedOperationException();
1562         }
1563 
1564         private transient Set<K> keySet;
1565         private transient Set<Map.Entry<K,V>> entrySet;
1566         private transient Collection<V> values;
1567 
1568         public Set<K> keySet() {
1569             if (keySet==null)
1570                 keySet = unmodifiableSet(m.keySet());
1571             return keySet;
1572         }
1573 
1574         public Set<Map.Entry<K,V>> entrySet() {
1575             if (entrySet==null)
1576                 entrySet = new UnmodifiableEntrySet<>(m.entrySet());
1577             return entrySet;
1578         }
1579 
1580         public Collection<V> values() {
1581             if (values==null)
1582                 values = unmodifiableCollection(m.values());
1583             return values;
1584         }
1585 
1586         public boolean equals(Object o) {return o == this || m.equals(o);}
1587         public int hashCode()           {return m.hashCode();}
1588         public String toString()        {return m.toString();}
1589 
1590         // Override default methods in Map
1591         @Override
1592         @SuppressWarnings("unchecked")
1593         public V getOrDefault(Object k, V defaultValue) {
1594             // Safe cast as we don't change the value
1595             return ((Map<K, V>)m).getOrDefault(k, defaultValue);
1596         }
1597 
1598         @Override
1599         public void forEach(BiConsumer<? super K, ? super V> action) {
1600             m.forEach(action);
1601         }
1602 
1603         @Override
1604         public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1605             throw new UnsupportedOperationException();
1606         }
1607 
1608         @Override
1609         public V putIfAbsent(K key, V value) {
1610             throw new UnsupportedOperationException();
1611         }
1612 
1613         @Override
1614         public boolean remove(Object key, Object value) {
1615             throw new UnsupportedOperationException();
1616         }
1617 
1618         @Override
1619         public boolean replace(K key, V oldValue, V newValue) {
1620             throw new UnsupportedOperationException();
1621         }
1622 
1623         @Override
1624         public V replace(K key, V value) {
1625             throw new UnsupportedOperationException();
1626         }
1627 
1628         @Override
1629         public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
1630             throw new UnsupportedOperationException();
1631         }
1632 
1633         @Override
1634         public V computeIfPresent(K key,
1635                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1636             throw new UnsupportedOperationException();
1637         }
1638 
1639         @Override
1640         public V compute(K key,
1641                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1642             throw new UnsupportedOperationException();
1643         }
1644 
1645         @Override
1646         public V merge(K key, V value,
1647                 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1648             throw new UnsupportedOperationException();
1649         }
1650 
1651         /**
1652          * We need this class in addition to UnmodifiableSet as
1653          * Map.Entries themselves permit modification of the backing Map
1654          * via their setValue operation.  This class is subtle: there are
1655          * many possible attacks that must be thwarted.
1656          *
1657          * @serial include
1658          */
1659         static class UnmodifiableEntrySet<K,V>
1660             extends UnmodifiableSet<Map.Entry<K,V>> {
1661             @java.io.Serial
1662             private static final long serialVersionUID = 7854390611657943733L;
1663 
1664             @SuppressWarnings({"unchecked", "rawtypes"})
1665             UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
1666                 // Need to cast to raw in order to work around a limitation in the type system
1667                 super((Set)s);
1668             }
1669 
1670             static <K, V> Consumer<Map.Entry<? extends K, ? extends V>> entryConsumer(
1671                     Consumer<? super Entry<K, V>> action) {
1672                 return e -> action.accept(new UnmodifiableEntry<>(e));
1673             }
1674 
1675             public void forEach(Consumer<? super Entry<K, V>> action) {
1676                 Objects.requireNonNull(action);
1677                 c.forEach(entryConsumer(action));
1678             }
1679 
1680             static final class UnmodifiableEntrySetSpliterator<K, V>
1681                     implements Spliterator<Entry<K,V>> {
1682                 final Spliterator<Map.Entry<K, V>> s;
1683 
1684                 UnmodifiableEntrySetSpliterator(Spliterator<Entry<K, V>> s) {
1685                     this.s = s;
1686                 }
1687 
1688                 @Override
1689                 public boolean tryAdvance(Consumer<? super Entry<K, V>> action) {
1690                     Objects.requireNonNull(action);
1691                     return s.tryAdvance(entryConsumer(action));
1692                 }
1693 
1694                 @Override
1695                 public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
1696                     Objects.requireNonNull(action);
1697                     s.forEachRemaining(entryConsumer(action));
1698                 }
1699 
1700                 @Override
1701                 public Spliterator<Entry<K, V>> trySplit() {
1702                     Spliterator<Entry<K, V>> split = s.trySplit();
1703                     return split == null
1704                            ? null
1705                            : new UnmodifiableEntrySetSpliterator<>(split);
1706                 }
1707 
1708                 @Override
1709                 public long estimateSize() {
1710                     return s.estimateSize();
1711                 }
1712 
1713                 @Override
1714                 public long getExactSizeIfKnown() {
1715                     return s.getExactSizeIfKnown();
1716                 }
1717 
1718                 @Override
1719                 public int characteristics() {
1720                     return s.characteristics();
1721                 }
1722 
1723                 @Override
1724                 public boolean hasCharacteristics(int characteristics) {
1725                     return s.hasCharacteristics(characteristics);
1726                 }
1727 
1728                 @Override
1729                 public Comparator<? super Entry<K, V>> getComparator() {
1730                     return s.getComparator();
1731                 }
1732             }
1733 
1734             @SuppressWarnings("unchecked")
1735             public Spliterator<Entry<K,V>> spliterator() {
1736                 return new UnmodifiableEntrySetSpliterator<>(
1737                         (Spliterator<Map.Entry<K, V>>) c.spliterator());
1738             }
1739 
1740             @Override
1741             public Stream<Entry<K,V>> stream() {
1742                 return StreamSupport.stream(spliterator(), false);
1743             }
1744 
1745             @Override
1746             public Stream<Entry<K,V>> parallelStream() {
1747                 return StreamSupport.stream(spliterator(), true);
1748             }
1749 
1750             public Iterator<Map.Entry<K,V>> iterator() {
1751                 return new Iterator<Map.Entry<K,V>>() {
1752                     private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
1753 
1754                     public boolean hasNext() {
1755                         return i.hasNext();
1756                     }
1757                     public Map.Entry<K,V> next() {
1758                         return new UnmodifiableEntry<>(i.next());
1759                     }
1760                     public void remove() {
1761                         throw new UnsupportedOperationException();
1762                     }
1763                     // Seems like an oversight. http://b/110351017
1764                     public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
1765                         i.forEachRemaining(entryConsumer(action));
1766                     }
1767                 };
1768             }
1769 
1770             @SuppressWarnings("unchecked")
1771             public Object[] toArray() {
1772                 Object[] a = c.toArray();
1773                 for (int i=0; i<a.length; i++)
1774                     a[i] = new UnmodifiableEntry<>((Map.Entry<? extends K, ? extends V>)a[i]);
1775                 return a;
1776             }
1777 
1778             @SuppressWarnings("unchecked")
1779             public <T> T[] toArray(T[] a) {
1780                 // We don't pass a to c.toArray, to avoid window of
1781                 // vulnerability wherein an unscrupulous multithreaded client
1782                 // could get his hands on raw (unwrapped) Entries from c.
1783                 Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
1784 
1785                 for (int i=0; i<arr.length; i++)
1786                     arr[i] = new UnmodifiableEntry<>((Map.Entry<? extends K, ? extends V>)arr[i]);
1787 
1788                 if (arr.length > a.length)
1789                     return (T[])arr;
1790 
1791                 System.arraycopy(arr, 0, a, 0, arr.length);
1792                 if (a.length > arr.length)
1793                     a[arr.length] = null;
1794                 return a;
1795             }
1796 
1797             /**
1798              * This method is overridden to protect the backing set against
1799              * an object with a nefarious equals function that senses
1800              * that the equality-candidate is Map.Entry and calls its
1801              * setValue method.
1802              */
1803             public boolean contains(Object o) {
1804                 if (!(o instanceof Map.Entry))
1805                     return false;
1806                 return c.contains(
1807                     new UnmodifiableEntry<>((Map.Entry<?,?>) o));
1808             }
1809 
1810             /**
1811              * The next two methods are overridden to protect against
1812              * an unscrupulous List whose contains(Object o) method senses
1813              * when o is a Map.Entry, and calls o.setValue.
1814              */
1815             public boolean containsAll(Collection<?> coll) {
1816                 for (Object e : coll) {
1817                     if (!contains(e)) // Invokes safe contains() above
1818                         return false;
1819                 }
1820                 return true;
1821             }
1822             public boolean equals(Object o) {
1823                 if (o == this)
1824                     return true;
1825 
1826                 // Android-changed: (b/247094511) instanceof pattern variable is not yet supported.
1827                 /*
1828                 return o instanceof Set<?> s
1829                         && s.size() == c.size()
1830                         && containsAll(s); // Invokes safe containsAll() above
1831                  */
1832                 if (!(o instanceof Set))
1833                     return false;
1834                 Set<?> s = (Set<?>) o;
1835                 if (s.size() != c.size())
1836                     return false;
1837                 return containsAll(s); // Invokes safe containsAll() above
1838             }
1839 
1840             /**
1841              * This "wrapper class" serves two purposes: it prevents
1842              * the client from modifying the backing Map, by short-circuiting
1843              * the setValue method, and it protects the backing Map against
1844              * an ill-behaved Map.Entry that attempts to modify another
1845              * Map Entry when asked to perform an equality check.
1846              */
1847             private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
1848                 private Map.Entry<? extends K, ? extends V> e;
1849 
1850                 UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e)
1851                         {this.e = Objects.requireNonNull(e);}
1852 
1853                 public K getKey()        {return e.getKey();}
1854                 public V getValue()      {return e.getValue();}
1855                 public V setValue(V value) {
1856                     throw new UnsupportedOperationException();
1857                 }
1858                 public int hashCode()    {return e.hashCode();}
1859                 public boolean equals(Object o) {
1860                     if (this == o)
1861                         return true;
1862                     // Android-changed: (b/247094511) instanceof pattern variable is not yet
1863                     // supported.
1864                     /*
1865                     return o instanceof Map.Entry<?, ?> t
1866                             && eq(e.getKey(),   t.getKey())
1867                             && eq(e.getValue(), t.getValue());
1868                     */
1869                     if (!(o instanceof Map.Entry))
1870                         return false;
1871                     Map.Entry<?,?> t = (Map.Entry<?,?>)o;
1872                     return eq(e.getKey(),   t.getKey()) &&
1873                             eq(e.getValue(), t.getValue());
1874                 }
1875                 public String toString() {return e.toString();}
1876             }
1877         }
1878     }
1879 
1880     /**
1881      * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1882      * specified sorted map. Query operations on the returned sorted map "read through"
1883      * to the specified sorted map.  Attempts to modify the returned
1884      * sorted map, whether direct, via its collection views, or via its
1885      * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in
1886      * an {@code UnsupportedOperationException}.<p>
1887      *
1888      * The returned sorted map will be serializable if the specified sorted map
1889      * is serializable.
1890      *
1891      * @implNote This method may return its argument if the argument is already unmodifiable.
1892      * @param <K> the class of the map keys
1893      * @param <V> the class of the map values
1894      * @param m the sorted map for which an unmodifiable view is to be
1895      *        returned.
1896      * @return an unmodifiable view of the specified sorted map.
1897      */
1898     @SuppressWarnings("unchecked")
1899     public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1900         // Not checking for subclasses because of heap pollution and information leakage.
1901         if (m.getClass() == UnmodifiableSortedMap.class) {
1902             return (SortedMap<K,V>) m;
1903         }
1904         return new UnmodifiableSortedMap<>(m);
1905     }
1906 
1907     /**
1908      * @serial include
1909      */
1910     static class UnmodifiableSortedMap<K,V>
1911           extends UnmodifiableMap<K,V>
1912           implements SortedMap<K,V>, Serializable {
1913         @java.io.Serial
1914         private static final long serialVersionUID = -8806743815996713206L;
1915 
1916         @SuppressWarnings("serial") // Conditionally serializable
1917         private final SortedMap<K, ? extends V> sm;
1918 
1919         UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m; }
1920         public Comparator<? super K> comparator()   { return sm.comparator(); }
1921         public SortedMap<K,V> subMap(K fromKey, K toKey)
1922              { return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); }
1923         public SortedMap<K,V> headMap(K toKey)
1924                      { return new UnmodifiableSortedMap<>(sm.headMap(toKey)); }
1925         public SortedMap<K,V> tailMap(K fromKey)
1926                    { return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); }
1927         public K firstKey()                           { return sm.firstKey(); }
1928         public K lastKey()                             { return sm.lastKey(); }
1929     }
1930 
1931     /**
1932      * Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
1933      * specified navigable map. Query operations on the returned navigable map "read
1934      * through" to the specified navigable map.  Attempts to modify the returned
1935      * navigable map, whether direct, via its collection views, or via its
1936      * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in
1937      * an {@code UnsupportedOperationException}.<p>
1938      *
1939      * The returned navigable map will be serializable if the specified
1940      * navigable map is serializable.
1941      *
1942      * @implNote This method may return its argument if the argument is already unmodifiable.
1943      * @param <K> the class of the map keys
1944      * @param <V> the class of the map values
1945      * @param m the navigable map for which an unmodifiable view is to be
1946      *        returned
1947      * @return an unmodifiable view of the specified navigable map
1948      * @since 1.8
1949      */
1950     @SuppressWarnings("unchecked")
1951     public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {
1952         if (m.getClass() == UnmodifiableNavigableMap.class) {
1953             return (NavigableMap<K,V>) m;
1954         }
1955         return new UnmodifiableNavigableMap<>(m);
1956     }
1957 
1958     /**
1959      * @serial include
1960      */
1961     static class UnmodifiableNavigableMap<K,V>
1962           extends UnmodifiableSortedMap<K,V>
1963           implements NavigableMap<K,V>, Serializable {
1964         @java.io.Serial
1965         private static final long serialVersionUID = -4858195264774772197L;
1966 
1967         /**
1968          * A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve
1969          * to preserve singleton property.
1970          *
1971          * @param <K> type of keys, if there were any, and of bounds
1972          * @param <V> type of values, if there were any
1973          */
1974         private static class EmptyNavigableMap<K,V> extends UnmodifiableNavigableMap<K,V>
1975             implements Serializable {
1976 
1977             @java.io.Serial
1978             private static final long serialVersionUID = -2239321462712562324L;
1979 
1980             EmptyNavigableMap()                       { super(new TreeMap<>()); }
1981 
1982             @Override
1983             public NavigableSet<K> navigableKeySet()
1984                                                 { return emptyNavigableSet(); }
1985 
1986             @java.io.Serial
1987             private Object readResolve()        { return EMPTY_NAVIGABLE_MAP; }
1988         }
1989 
1990         /**
1991          * Singleton for {@link emptyNavigableMap()} which is also immutable.
1992          */
1993         private static final EmptyNavigableMap<?,?> EMPTY_NAVIGABLE_MAP =
1994             new EmptyNavigableMap<>();
1995 
1996         /**
1997          * The instance we wrap and protect.
1998          */
1999         @SuppressWarnings("serial") // Conditionally serializable
2000         private final NavigableMap<K, ? extends V> nm;
2001 
2002         UnmodifiableNavigableMap(NavigableMap<K, ? extends V> m)
2003                                                             {super(m); nm = m;}
2004 
2005         public K lowerKey(K key)                   { return nm.lowerKey(key); }
2006         public K floorKey(K key)                   { return nm.floorKey(key); }
2007         public K ceilingKey(K key)               { return nm.ceilingKey(key); }
2008         public K higherKey(K key)                 { return nm.higherKey(key); }
2009 
2010         @SuppressWarnings("unchecked")
2011         public Entry<K, V> lowerEntry(K key) {
2012             Entry<K,V> lower = (Entry<K, V>) nm.lowerEntry(key);
2013             return (null != lower)
2014                 ? new UnmodifiableEntrySet.UnmodifiableEntry<>(lower)
2015                 : null;
2016         }
2017 
2018         @SuppressWarnings("unchecked")
2019         public Entry<K, V> floorEntry(K key) {
2020             Entry<K,V> floor = (Entry<K, V>) nm.floorEntry(key);
2021             return (null != floor)
2022                 ? new UnmodifiableEntrySet.UnmodifiableEntry<>(floor)
2023                 : null;
2024         }
2025 
2026         @SuppressWarnings("unchecked")
2027         public Entry<K, V> ceilingEntry(K key) {
2028             Entry<K,V> ceiling = (Entry<K, V>) nm.ceilingEntry(key);
2029             return (null != ceiling)
2030                 ? new UnmodifiableEntrySet.UnmodifiableEntry<>(ceiling)
2031                 : null;
2032         }
2033 
2034 
2035         @SuppressWarnings("unchecked")
2036         public Entry<K, V> higherEntry(K key) {
2037             Entry<K,V> higher = (Entry<K, V>) nm.higherEntry(key);
2038             return (null != higher)
2039                 ? new UnmodifiableEntrySet.UnmodifiableEntry<>(higher)
2040                 : null;
2041         }
2042 
2043         @SuppressWarnings("unchecked")
2044         public Entry<K, V> firstEntry() {
2045             Entry<K,V> first = (Entry<K, V>) nm.firstEntry();
2046             return (null != first)
2047                 ? new UnmodifiableEntrySet.UnmodifiableEntry<>(first)
2048                 : null;
2049         }
2050 
2051         @SuppressWarnings("unchecked")
2052         public Entry<K, V> lastEntry() {
2053             Entry<K,V> last = (Entry<K, V>) nm.lastEntry();
2054             return (null != last)
2055                 ? new UnmodifiableEntrySet.UnmodifiableEntry<>(last)
2056                 : null;
2057         }
2058 
2059         public Entry<K, V> pollFirstEntry()
2060                                  { throw new UnsupportedOperationException(); }
2061         public Entry<K, V> pollLastEntry()
2062                                  { throw new UnsupportedOperationException(); }
2063         public NavigableMap<K, V> descendingMap()
2064                        { return unmodifiableNavigableMap(nm.descendingMap()); }
2065         public NavigableSet<K> navigableKeySet()
2066                      { return unmodifiableNavigableSet(nm.navigableKeySet()); }
2067         public NavigableSet<K> descendingKeySet()
2068                     { return unmodifiableNavigableSet(nm.descendingKeySet()); }
2069 
2070         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
2071             return unmodifiableNavigableMap(
2072                 nm.subMap(fromKey, fromInclusive, toKey, toInclusive));
2073         }
2074 
2075         public NavigableMap<K, V> headMap(K toKey, boolean inclusive)
2076              { return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); }
2077         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive)
2078            { return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); }
2079     }
2080 
2081     // Synch Wrappers
2082 
2083     /**
2084      * Returns a synchronized (thread-safe) collection backed by the specified
2085      * collection.  In order to guarantee serial access, it is critical that
2086      * <strong>all</strong> access to the backing collection is accomplished
2087      * through the returned collection.<p>
2088      *
2089      * It is imperative that the user manually synchronize on the returned
2090      * collection when traversing it via {@link Iterator}, {@link Spliterator}
2091      * or {@link Stream}:
2092      * <pre>
2093      *  Collection c = Collections.synchronizedCollection(myCollection);
2094      *     ...
2095      *  synchronized (c) {
2096      *      Iterator i = c.iterator(); // Must be in the synchronized block
2097      *      while (i.hasNext())
2098      *         foo(i.next());
2099      *  }
2100      * </pre>
2101      * Failure to follow this advice may result in non-deterministic behavior.
2102      *
2103      * <p>The returned collection does <i>not</i> pass the {@code hashCode}
2104      * and {@code equals} operations through to the backing collection, but
2105      * relies on {@code Object}'s equals and hashCode methods.  This is
2106      * necessary to preserve the contracts of these operations in the case
2107      * that the backing collection is a set or a list.<p>
2108      *
2109      * The returned collection will be serializable if the specified collection
2110      * is serializable.
2111      *
2112      * @param  <T> the class of the objects in the collection
2113      * @param  c the collection to be "wrapped" in a synchronized collection.
2114      * @return a synchronized view of the specified collection.
2115      */
2116     public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
2117         return new SynchronizedCollection<>(c);
2118     }
2119 
2120     static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
2121         return new SynchronizedCollection<>(c, mutex);
2122     }
2123 
2124     /**
2125      * @serial include
2126      */
2127     static class SynchronizedCollection<E> implements Collection<E>, Serializable {
2128         @java.io.Serial
2129         private static final long serialVersionUID = 3053995032091335093L;
2130 
2131         @SuppressWarnings("serial") // Conditionally serializable
2132         final Collection<E> c;  // Backing Collection
2133         @SuppressWarnings("serial") // Conditionally serializable
2134         final Object mutex;     // Object on which to synchronize
2135 
2136         SynchronizedCollection(Collection<E> c) {
2137             this.c = Objects.requireNonNull(c);
2138             mutex = this;
2139         }
2140 
2141         SynchronizedCollection(Collection<E> c, Object mutex) {
2142             this.c = Objects.requireNonNull(c);
2143             this.mutex = Objects.requireNonNull(mutex);
2144         }
2145 
2146         public int size() {
2147             synchronized (mutex) {return c.size();}
2148         }
2149         public boolean isEmpty() {
2150             synchronized (mutex) {return c.isEmpty();}
2151         }
2152         public boolean contains(Object o) {
2153             synchronized (mutex) {return c.contains(o);}
2154         }
2155         public Object[] toArray() {
2156             synchronized (mutex) {return c.toArray();}
2157         }
2158         public <T> T[] toArray(T[] a) {
2159             synchronized (mutex) {return c.toArray(a);}
2160         }
2161         public <T> T[] toArray(IntFunction<T[]> f) {
2162             synchronized (mutex) {return c.toArray(f);}
2163         }
2164 
2165         public Iterator<E> iterator() {
2166             return c.iterator(); // Must be manually synched by user!
2167         }
2168 
2169         public boolean add(E e) {
2170             synchronized (mutex) {return c.add(e);}
2171         }
2172         public boolean remove(Object o) {
2173             synchronized (mutex) {return c.remove(o);}
2174         }
2175 
2176         public boolean containsAll(Collection<?> coll) {
2177             synchronized (mutex) {return c.containsAll(coll);}
2178         }
2179         public boolean addAll(Collection<? extends E> coll) {
2180             synchronized (mutex) {return c.addAll(coll);}
2181         }
2182         public boolean removeAll(Collection<?> coll) {
2183             synchronized (mutex) {return c.removeAll(coll);}
2184         }
2185         public boolean retainAll(Collection<?> coll) {
2186             synchronized (mutex) {return c.retainAll(coll);}
2187         }
2188         public void clear() {
2189             synchronized (mutex) {c.clear();}
2190         }
2191         public String toString() {
2192             synchronized (mutex) {return c.toString();}
2193         }
2194         // Override default methods in Collection
2195         @Override
2196         public void forEach(Consumer<? super E> consumer) {
2197             synchronized (mutex) {c.forEach(consumer);}
2198         }
2199         @Override
2200         public boolean removeIf(Predicate<? super E> filter) {
2201             synchronized (mutex) {return c.removeIf(filter);}
2202         }
2203         @Override
2204         public Spliterator<E> spliterator() {
2205             return c.spliterator(); // Must be manually synched by user!
2206         }
2207         @Override
2208         public Stream<E> stream() {
2209             return c.stream(); // Must be manually synched by user!
2210         }
2211         @Override
2212         public Stream<E> parallelStream() {
2213             return c.parallelStream(); // Must be manually synched by user!
2214         }
2215         @java.io.Serial
2216         private void writeObject(ObjectOutputStream s) throws IOException {
2217             synchronized (mutex) {s.defaultWriteObject();}
2218         }
2219     }
2220 
2221     /**
2222      * Returns a synchronized (thread-safe) set backed by the specified
2223      * set.  In order to guarantee serial access, it is critical that
2224      * <strong>all</strong> access to the backing set is accomplished
2225      * through the returned set.<p>
2226      *
2227      * It is imperative that the user manually synchronize on the returned
2228      * collection when traversing it via {@link Iterator}, {@link Spliterator}
2229      * or {@link Stream}:
2230      * <pre>
2231      *  Set s = Collections.synchronizedSet(new HashSet());
2232      *      ...
2233      *  synchronized (s) {
2234      *      Iterator i = s.iterator(); // Must be in the synchronized block
2235      *      while (i.hasNext())
2236      *          foo(i.next());
2237      *  }
2238      * </pre>
2239      * Failure to follow this advice may result in non-deterministic behavior.
2240      *
2241      * <p>The returned set will be serializable if the specified set is
2242      * serializable.
2243      *
2244      * @param  <T> the class of the objects in the set
2245      * @param  s the set to be "wrapped" in a synchronized set.
2246      * @return a synchronized view of the specified set.
2247      */
2248     public static <T> Set<T> synchronizedSet(Set<T> s) {
2249         return new SynchronizedSet<>(s);
2250     }
2251 
2252     static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
2253         return new SynchronizedSet<>(s, mutex);
2254     }
2255 
2256     /**
2257      * @serial include
2258      */
2259     static class SynchronizedSet<E>
2260           extends SynchronizedCollection<E>
2261           implements Set<E> {
2262         @java.io.Serial
2263         private static final long serialVersionUID = 487447009682186044L;
2264 
2265         SynchronizedSet(Set<E> s) {
2266             super(s);
2267         }
2268         SynchronizedSet(Set<E> s, Object mutex) {
2269             super(s, mutex);
2270         }
2271 
2272         public boolean equals(Object o) {
2273             if (this == o)
2274                 return true;
2275             synchronized (mutex) {return c.equals(o);}
2276         }
2277         public int hashCode() {
2278             synchronized (mutex) {return c.hashCode();}
2279         }
2280     }
2281 
2282     /**
2283      * Returns a synchronized (thread-safe) sorted set backed by the specified
2284      * sorted set.  In order to guarantee serial access, it is critical that
2285      * <strong>all</strong> access to the backing sorted set is accomplished
2286      * through the returned sorted set (or its views).<p>
2287      *
2288      * It is imperative that the user manually synchronize on the returned
2289      * sorted set when traversing it or any of its {@code subSet},
2290      * {@code headSet}, or {@code tailSet} views via {@link Iterator},
2291      * {@link Spliterator} or {@link Stream}:
2292      * <pre>
2293      *  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
2294      *      ...
2295      *  synchronized (s) {
2296      *      Iterator i = s.iterator(); // Must be in the synchronized block
2297      *      while (i.hasNext())
2298      *          foo(i.next());
2299      *  }
2300      * </pre>
2301      * or:
2302      * <pre>
2303      *  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
2304      *  SortedSet s2 = s.headSet(foo);
2305      *      ...
2306      *  synchronized (s) {  // Note: s, not s2!!!
2307      *      Iterator i = s2.iterator(); // Must be in the synchronized block
2308      *      while (i.hasNext())
2309      *          foo(i.next());
2310      *  }
2311      * </pre>
2312      * Failure to follow this advice may result in non-deterministic behavior.
2313      *
2314      * <p>The returned sorted set will be serializable if the specified
2315      * sorted set is serializable.
2316      *
2317      * @param  <T> the class of the objects in the set
2318      * @param  s the sorted set to be "wrapped" in a synchronized sorted set.
2319      * @return a synchronized view of the specified sorted set.
2320      */
2321     public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
2322         return new SynchronizedSortedSet<>(s);
2323     }
2324 
2325     /**
2326      * @serial include
2327      */
2328     static class SynchronizedSortedSet<E>
2329         extends SynchronizedSet<E>
2330         implements SortedSet<E>
2331     {
2332         @java.io.Serial
2333         private static final long serialVersionUID = 8695801310862127406L;
2334 
2335         @SuppressWarnings("serial") // Conditionally serializable
2336         private final SortedSet<E> ss;
2337 
2338         SynchronizedSortedSet(SortedSet<E> s) {
2339             super(s);
2340             ss = s;
2341         }
2342         SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
2343             super(s, mutex);
2344             ss = s;
2345         }
2346 
2347         public Comparator<? super E> comparator() {
2348             synchronized (mutex) {return ss.comparator();}
2349         }
2350 
2351         public SortedSet<E> subSet(E fromElement, E toElement) {
2352             synchronized (mutex) {
2353                 return new SynchronizedSortedSet<>(
2354                     ss.subSet(fromElement, toElement), mutex);
2355             }
2356         }
2357         public SortedSet<E> headSet(E toElement) {
2358             synchronized (mutex) {
2359                 return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
2360             }
2361         }
2362         public SortedSet<E> tailSet(E fromElement) {
2363             synchronized (mutex) {
2364                return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
2365             }
2366         }
2367 
2368         public E first() {
2369             synchronized (mutex) {return ss.first();}
2370         }
2371         public E last() {
2372             synchronized (mutex) {return ss.last();}
2373         }
2374     }
2375 
2376     /**
2377      * Returns a synchronized (thread-safe) navigable set backed by the
2378      * specified navigable set.  In order to guarantee serial access, it is
2379      * critical that <strong>all</strong> access to the backing navigable set is
2380      * accomplished through the returned navigable set (or its views).<p>
2381      *
2382      * It is imperative that the user manually synchronize on the returned
2383      * navigable set when traversing it, or any of its {@code subSet},
2384      * {@code headSet}, or {@code tailSet} views, via {@link Iterator},
2385      * {@link Spliterator} or {@link Stream}:
2386      * <pre>
2387      *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
2388      *      ...
2389      *  synchronized (s) {
2390      *      Iterator i = s.iterator(); // Must be in the synchronized block
2391      *      while (i.hasNext())
2392      *          foo(i.next());
2393      *  }
2394      * </pre>
2395      * or:
2396      * <pre>
2397      *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
2398      *  NavigableSet s2 = s.headSet(foo, true);
2399      *      ...
2400      *  synchronized (s) {  // Note: s, not s2!!!
2401      *      Iterator i = s2.iterator(); // Must be in the synchronized block
2402      *      while (i.hasNext())
2403      *          foo(i.next());
2404      *  }
2405      * </pre>
2406      * Failure to follow this advice may result in non-deterministic behavior.
2407      *
2408      * <p>The returned navigable set will be serializable if the specified
2409      * navigable set is serializable.
2410      *
2411      * @param  <T> the class of the objects in the set
2412      * @param  s the navigable set to be "wrapped" in a synchronized navigable
2413      * set
2414      * @return a synchronized view of the specified navigable set
2415      * @since 1.8
2416      */
2417     public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s) {
2418         return new SynchronizedNavigableSet<>(s);
2419     }
2420 
2421     /**
2422      * @serial include
2423      */
2424     static class SynchronizedNavigableSet<E>
2425         extends SynchronizedSortedSet<E>
2426         implements NavigableSet<E>
2427     {
2428         @java.io.Serial
2429         private static final long serialVersionUID = -5505529816273629798L;
2430 
2431         @SuppressWarnings("serial") // Conditionally serializable
2432         private final NavigableSet<E> ns;
2433 
2434         SynchronizedNavigableSet(NavigableSet<E> s) {
2435             super(s);
2436             ns = s;
2437         }
2438 
2439         SynchronizedNavigableSet(NavigableSet<E> s, Object mutex) {
2440             super(s, mutex);
2441             ns = s;
2442         }
2443         public E lower(E e)      { synchronized (mutex) {return ns.lower(e);} }
2444         public E floor(E e)      { synchronized (mutex) {return ns.floor(e);} }
2445         public E ceiling(E e)  { synchronized (mutex) {return ns.ceiling(e);} }
2446         public E higher(E e)    { synchronized (mutex) {return ns.higher(e);} }
2447         public E pollFirst()  { synchronized (mutex) {return ns.pollFirst();} }
2448         public E pollLast()    { synchronized (mutex) {return ns.pollLast();} }
2449 
2450         public NavigableSet<E> descendingSet() {
2451             synchronized (mutex) {
2452                 return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex);
2453             }
2454         }
2455 
2456         public Iterator<E> descendingIterator()
2457                  { synchronized (mutex) { return descendingSet().iterator(); } }
2458 
2459         public NavigableSet<E> subSet(E fromElement, E toElement) {
2460             synchronized (mutex) {
2461                 return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex);
2462             }
2463         }
2464         public NavigableSet<E> headSet(E toElement) {
2465             synchronized (mutex) {
2466                 return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex);
2467             }
2468         }
2469         public NavigableSet<E> tailSet(E fromElement) {
2470             synchronized (mutex) {
2471                 return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, true), mutex);
2472             }
2473         }
2474 
2475         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
2476             synchronized (mutex) {
2477                 return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex);
2478             }
2479         }
2480 
2481         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
2482             synchronized (mutex) {
2483                 return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex);
2484             }
2485         }
2486 
2487         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
2488             synchronized (mutex) {
2489                 return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive), mutex);
2490             }
2491         }
2492     }
2493 
2494     /**
2495      * Returns a synchronized (thread-safe) list backed by the specified
2496      * list.  In order to guarantee serial access, it is critical that
2497      * <strong>all</strong> access to the backing list is accomplished
2498      * through the returned list.<p>
2499      *
2500      * It is imperative that the user manually synchronize on the returned
2501      * list when traversing it via {@link Iterator}, {@link Spliterator}
2502      * or {@link Stream}:
2503      * <pre>
2504      *  List list = Collections.synchronizedList(new ArrayList());
2505      *      ...
2506      *  synchronized (list) {
2507      *      Iterator i = list.iterator(); // Must be in synchronized block
2508      *      while (i.hasNext())
2509      *          foo(i.next());
2510      *  }
2511      * </pre>
2512      * Failure to follow this advice may result in non-deterministic behavior.
2513      *
2514      * <p>The returned list will be serializable if the specified list is
2515      * serializable.
2516      *
2517      * @param  <T> the class of the objects in the list
2518      * @param  list the list to be "wrapped" in a synchronized list.
2519      * @return a synchronized view of the specified list.
2520      */
2521     public static <T> List<T> synchronizedList(List<T> list) {
2522         return (list instanceof RandomAccess ?
2523                 new SynchronizedRandomAccessList<>(list) :
2524                 new SynchronizedList<>(list));
2525     }
2526 
2527     static <T> List<T> synchronizedList(List<T> list, Object mutex) {
2528         return (list instanceof RandomAccess ?
2529                 new SynchronizedRandomAccessList<>(list, mutex) :
2530                 new SynchronizedList<>(list, mutex));
2531     }
2532 
2533     /**
2534      * @serial include
2535      */
2536     static class SynchronizedList<E>
2537         extends SynchronizedCollection<E>
2538         implements List<E> {
2539         @java.io.Serial
2540         private static final long serialVersionUID = -7754090372962971524L;
2541 
2542         @SuppressWarnings("serial") // Conditionally serializable
2543         final List<E> list;
2544 
2545         SynchronizedList(List<E> list) {
2546             super(list);
2547             this.list = list;
2548         }
2549         SynchronizedList(List<E> list, Object mutex) {
2550             super(list, mutex);
2551             this.list = list;
2552         }
2553 
2554         public boolean equals(Object o) {
2555             if (this == o)
2556                 return true;
2557             synchronized (mutex) {return list.equals(o);}
2558         }
2559         public int hashCode() {
2560             synchronized (mutex) {return list.hashCode();}
2561         }
2562 
2563         public E get(int index) {
2564             synchronized (mutex) {return list.get(index);}
2565         }
2566         public E set(int index, E element) {
2567             synchronized (mutex) {return list.set(index, element);}
2568         }
2569         public void add(int index, E element) {
2570             synchronized (mutex) {list.add(index, element);}
2571         }
2572         public E remove(int index) {
2573             synchronized (mutex) {return list.remove(index);}
2574         }
2575 
2576         public int indexOf(Object o) {
2577             synchronized (mutex) {return list.indexOf(o);}
2578         }
2579         public int lastIndexOf(Object o) {
2580             synchronized (mutex) {return list.lastIndexOf(o);}
2581         }
2582 
2583         public boolean addAll(int index, Collection<? extends E> c) {
2584             synchronized (mutex) {return list.addAll(index, c);}
2585         }
2586 
2587         public ListIterator<E> listIterator() {
2588             return list.listIterator(); // Must be manually synched by user
2589         }
2590 
2591         public ListIterator<E> listIterator(int index) {
2592             return list.listIterator(index); // Must be manually synched by user
2593         }
2594 
2595         public List<E> subList(int fromIndex, int toIndex) {
2596             synchronized (mutex) {
2597                 return new SynchronizedList<>(list.subList(fromIndex, toIndex),
2598                                             mutex);
2599             }
2600         }
2601 
2602         @Override
2603         public void replaceAll(UnaryOperator<E> operator) {
2604             synchronized (mutex) {list.replaceAll(operator);}
2605         }
2606         @Override
2607         public void sort(Comparator<? super E> c) {
2608             synchronized (mutex) {list.sort(c);}
2609         }
2610 
2611         /**
2612          * SynchronizedRandomAccessList instances are serialized as
2613          * SynchronizedList instances to allow them to be deserialized
2614          * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
2615          * This method inverts the transformation.  As a beneficial
2616          * side-effect, it also grafts the RandomAccess marker onto
2617          * SynchronizedList instances that were serialized in pre-1.4 JREs.
2618          *
2619          * Note: Unfortunately, SynchronizedRandomAccessList instances
2620          * serialized in 1.4.1 and deserialized in 1.4 will become
2621          * SynchronizedList instances, as this method was missing in 1.4.
2622          */
2623         @java.io.Serial
2624         private Object readResolve() {
2625             return (list instanceof RandomAccess
2626                     ? new SynchronizedRandomAccessList<>(list)
2627                     : this);
2628         }
2629     }
2630 
2631     /**
2632      * @serial include
2633      */
2634     static class SynchronizedRandomAccessList<E>
2635         extends SynchronizedList<E>
2636         implements RandomAccess {
2637 
2638         SynchronizedRandomAccessList(List<E> list) {
2639             super(list);
2640         }
2641 
2642         SynchronizedRandomAccessList(List<E> list, Object mutex) {
2643             super(list, mutex);
2644         }
2645 
2646         public List<E> subList(int fromIndex, int toIndex) {
2647             synchronized (mutex) {
2648                 return new SynchronizedRandomAccessList<>(
2649                     list.subList(fromIndex, toIndex), mutex);
2650             }
2651         }
2652 
2653         @java.io.Serial
2654         private static final long serialVersionUID = 1530674583602358482L;
2655 
2656         /**
2657          * Allows instances to be deserialized in pre-1.4 JREs (which do
2658          * not have SynchronizedRandomAccessList).  SynchronizedList has
2659          * a readResolve method that inverts this transformation upon
2660          * deserialization.
2661          */
2662         @java.io.Serial
2663         private Object writeReplace() {
2664             return new SynchronizedList<>(list);
2665         }
2666     }
2667 
2668     /**
2669      * Returns a synchronized (thread-safe) map backed by the specified
2670      * map.  In order to guarantee serial access, it is critical that
2671      * <strong>all</strong> access to the backing map is accomplished
2672      * through the returned map.<p>
2673      *
2674      * It is imperative that the user manually synchronize on the returned
2675      * map when traversing any of its collection views via {@link Iterator},
2676      * {@link Spliterator} or {@link Stream}:
2677      * <pre>
2678      *  Map m = Collections.synchronizedMap(new HashMap());
2679      *      ...
2680      *  Set s = m.keySet();  // Needn't be in synchronized block
2681      *      ...
2682      *  synchronized (m) {  // Synchronizing on m, not s!
2683      *      Iterator i = s.iterator(); // Must be in synchronized block
2684      *      while (i.hasNext())
2685      *          foo(i.next());
2686      *  }
2687      * </pre>
2688      * Failure to follow this advice may result in non-deterministic behavior.
2689      *
2690      * <p>The returned map will be serializable if the specified map is
2691      * serializable.
2692      *
2693      * @param <K> the class of the map keys
2694      * @param <V> the class of the map values
2695      * @param  m the map to be "wrapped" in a synchronized map.
2696      * @return a synchronized view of the specified map.
2697      */
2698     public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
2699         return new SynchronizedMap<>(m);
2700     }
2701 
2702     /**
2703      * @serial include
2704      */
2705     private static class SynchronizedMap<K,V>
2706         implements Map<K,V>, Serializable {
2707         @java.io.Serial
2708         private static final long serialVersionUID = 1978198479659022715L;
2709 
2710         @SuppressWarnings("serial") // Conditionally serializable
2711         private final Map<K,V> m;     // Backing Map
2712         @SuppressWarnings("serial") // Conditionally serializable
2713         final Object      mutex;        // Object on which to synchronize
2714 
2715         SynchronizedMap(Map<K,V> m) {
2716             this.m = Objects.requireNonNull(m);
2717             mutex = this;
2718         }
2719 
2720         SynchronizedMap(Map<K,V> m, Object mutex) {
2721             this.m = m;
2722             this.mutex = mutex;
2723         }
2724 
2725         public int size() {
2726             synchronized (mutex) {return m.size();}
2727         }
2728         public boolean isEmpty() {
2729             synchronized (mutex) {return m.isEmpty();}
2730         }
2731         public boolean containsKey(Object key) {
2732             synchronized (mutex) {return m.containsKey(key);}
2733         }
2734         public boolean containsValue(Object value) {
2735             synchronized (mutex) {return m.containsValue(value);}
2736         }
2737         public V get(Object key) {
2738             synchronized (mutex) {return m.get(key);}
2739         }
2740 
2741         public V put(K key, V value) {
2742             synchronized (mutex) {return m.put(key, value);}
2743         }
2744         public V remove(Object key) {
2745             synchronized (mutex) {return m.remove(key);}
2746         }
2747         public void putAll(Map<? extends K, ? extends V> map) {
2748             synchronized (mutex) {m.putAll(map);}
2749         }
2750         public void clear() {
2751             synchronized (mutex) {m.clear();}
2752         }
2753 
2754         private transient Set<K> keySet;
2755         private transient Set<Map.Entry<K,V>> entrySet;
2756         private transient Collection<V> values;
2757 
2758         public Set<K> keySet() {
2759             synchronized (mutex) {
2760                 if (keySet==null)
2761                     keySet = new SynchronizedSet<>(m.keySet(), mutex);
2762                 return keySet;
2763             }
2764         }
2765 
2766         public Set<Map.Entry<K,V>> entrySet() {
2767             synchronized (mutex) {
2768                 if (entrySet==null)
2769                     entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
2770                 return entrySet;
2771             }
2772         }
2773 
2774         public Collection<V> values() {
2775             synchronized (mutex) {
2776                 if (values==null)
2777                     values = new SynchronizedCollection<>(m.values(), mutex);
2778                 return values;
2779             }
2780         }
2781 
2782         public boolean equals(Object o) {
2783             if (this == o)
2784                 return true;
2785             synchronized (mutex) {return m.equals(o);}
2786         }
2787         public int hashCode() {
2788             synchronized (mutex) {return m.hashCode();}
2789         }
2790         public String toString() {
2791             synchronized (mutex) {return m.toString();}
2792         }
2793 
2794         // Override default methods in Map
2795         @Override
2796         public V getOrDefault(Object k, V defaultValue) {
2797             synchronized (mutex) {return m.getOrDefault(k, defaultValue);}
2798         }
2799         @Override
2800         public void forEach(BiConsumer<? super K, ? super V> action) {
2801             synchronized (mutex) {m.forEach(action);}
2802         }
2803         @Override
2804         public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
2805             synchronized (mutex) {m.replaceAll(function);}
2806         }
2807         @Override
2808         public V putIfAbsent(K key, V value) {
2809             synchronized (mutex) {return m.putIfAbsent(key, value);}
2810         }
2811         @Override
2812         public boolean remove(Object key, Object value) {
2813             synchronized (mutex) {return m.remove(key, value);}
2814         }
2815         @Override
2816         public boolean replace(K key, V oldValue, V newValue) {
2817             synchronized (mutex) {return m.replace(key, oldValue, newValue);}
2818         }
2819         @Override
2820         public V replace(K key, V value) {
2821             synchronized (mutex) {return m.replace(key, value);}
2822         }
2823         @Override
2824         public V computeIfAbsent(K key,
2825                 Function<? super K, ? extends V> mappingFunction) {
2826             synchronized (mutex) {return m.computeIfAbsent(key, mappingFunction);}
2827         }
2828         @Override
2829         public V computeIfPresent(K key,
2830                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2831             synchronized (mutex) {return m.computeIfPresent(key, remappingFunction);}
2832         }
2833         @Override
2834         public V compute(K key,
2835                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2836             synchronized (mutex) {return m.compute(key, remappingFunction);}
2837         }
2838         @Override
2839         public V merge(K key, V value,
2840                 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2841             synchronized (mutex) {return m.merge(key, value, remappingFunction);}
2842         }
2843 
2844         @java.io.Serial
2845         private void writeObject(ObjectOutputStream s) throws IOException {
2846             synchronized (mutex) {s.defaultWriteObject();}
2847         }
2848     }
2849 
2850     /**
2851      * Returns a synchronized (thread-safe) sorted map backed by the specified
2852      * sorted map.  In order to guarantee serial access, it is critical that
2853      * <strong>all</strong> access to the backing sorted map is accomplished
2854      * through the returned sorted map (or its views).<p>
2855      *
2856      * It is imperative that the user manually synchronize on the returned
2857      * sorted map when traversing any of its collection views, or the
2858      * collections views of any of its {@code subMap}, {@code headMap} or
2859      * {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or
2860      * {@link Stream}:
2861      * <pre>
2862      *  SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2863      *      ...
2864      *  Set s = m.keySet();  // Needn't be in synchronized block
2865      *      ...
2866      *  synchronized (m) {  // Synchronizing on m, not s!
2867      *      Iterator i = s.iterator(); // Must be in synchronized block
2868      *      while (i.hasNext())
2869      *          foo(i.next());
2870      *  }
2871      * </pre>
2872      * or:
2873      * <pre>
2874      *  SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2875      *  SortedMap m2 = m.subMap(foo, bar);
2876      *      ...
2877      *  Set s2 = m2.keySet();  // Needn't be in synchronized block
2878      *      ...
2879      *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
2880      *      Iterator i = s2.iterator(); // Must be in synchronized block
2881      *      while (i.hasNext())
2882      *          foo(i.next());
2883      *  }
2884      * </pre>
2885      * Failure to follow this advice may result in non-deterministic behavior.
2886      *
2887      * <p>The returned sorted map will be serializable if the specified
2888      * sorted map is serializable.
2889      *
2890      * @param <K> the class of the map keys
2891      * @param <V> the class of the map values
2892      * @param  m the sorted map to be "wrapped" in a synchronized sorted map.
2893      * @return a synchronized view of the specified sorted map.
2894      */
2895     public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
2896         return new SynchronizedSortedMap<>(m);
2897     }
2898 
2899     /**
2900      * @serial include
2901      */
2902     static class SynchronizedSortedMap<K,V>
2903         extends SynchronizedMap<K,V>
2904         implements SortedMap<K,V>
2905     {
2906         @java.io.Serial
2907         private static final long serialVersionUID = -8798146769416483793L;
2908 
2909         @SuppressWarnings("serial") // Conditionally serializable
2910         private final SortedMap<K,V> sm;
2911 
2912         SynchronizedSortedMap(SortedMap<K,V> m) {
2913             super(m);
2914             sm = m;
2915         }
2916         SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
2917             super(m, mutex);
2918             sm = m;
2919         }
2920 
2921         public Comparator<? super K> comparator() {
2922             synchronized (mutex) {return sm.comparator();}
2923         }
2924 
2925         public SortedMap<K,V> subMap(K fromKey, K toKey) {
2926             synchronized (mutex) {
2927                 return new SynchronizedSortedMap<>(
2928                     sm.subMap(fromKey, toKey), mutex);
2929             }
2930         }
2931         public SortedMap<K,V> headMap(K toKey) {
2932             synchronized (mutex) {
2933                 return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);
2934             }
2935         }
2936         public SortedMap<K,V> tailMap(K fromKey) {
2937             synchronized (mutex) {
2938                return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);
2939             }
2940         }
2941 
2942         public K firstKey() {
2943             synchronized (mutex) {return sm.firstKey();}
2944         }
2945         public K lastKey() {
2946             synchronized (mutex) {return sm.lastKey();}
2947         }
2948     }
2949 
2950     /**
2951      * Returns a synchronized (thread-safe) navigable map backed by the
2952      * specified navigable map.  In order to guarantee serial access, it is
2953      * critical that <strong>all</strong> access to the backing navigable map is
2954      * accomplished through the returned navigable map (or its views).<p>
2955      *
2956      * It is imperative that the user manually synchronize on the returned
2957      * navigable map when traversing any of its collection views, or the
2958      * collections views of any of its {@code subMap}, {@code headMap} or
2959      * {@code tailMap} views, via {@link Iterator}, {@link Spliterator} or
2960      * {@link Stream}:
2961      * <pre>
2962      *  NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
2963      *      ...
2964      *  Set s = m.keySet();  // Needn't be in synchronized block
2965      *      ...
2966      *  synchronized (m) {  // Synchronizing on m, not s!
2967      *      Iterator i = s.iterator(); // Must be in synchronized block
2968      *      while (i.hasNext())
2969      *          foo(i.next());
2970      *  }
2971      * </pre>
2972      * or:
2973      * <pre>
2974      *  NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
2975      *  NavigableMap m2 = m.subMap(foo, true, bar, false);
2976      *      ...
2977      *  Set s2 = m2.keySet();  // Needn't be in synchronized block
2978      *      ...
2979      *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
2980      *      Iterator i = s.iterator(); // Must be in synchronized block
2981      *      while (i.hasNext())
2982      *          foo(i.next());
2983      *  }
2984      * </pre>
2985      * Failure to follow this advice may result in non-deterministic behavior.
2986      *
2987      * <p>The returned navigable map will be serializable if the specified
2988      * navigable map is serializable.
2989      *
2990      * @param <K> the class of the map keys
2991      * @param <V> the class of the map values
2992      * @param  m the navigable map to be "wrapped" in a synchronized navigable
2993      *              map
2994      * @return a synchronized view of the specified navigable map.
2995      * @since 1.8
2996      */
2997     public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m) {
2998         return new SynchronizedNavigableMap<>(m);
2999     }
3000 
3001     /**
3002      * A synchronized NavigableMap.
3003      *
3004      * @serial include
3005      */
3006     static class SynchronizedNavigableMap<K,V>
3007         extends SynchronizedSortedMap<K,V>
3008         implements NavigableMap<K,V>
3009     {
3010         @java.io.Serial
3011         private static final long serialVersionUID = 699392247599746807L;
3012 
3013         @SuppressWarnings("serial") // Conditionally serializable
3014         private final NavigableMap<K,V> nm;
3015 
3016         SynchronizedNavigableMap(NavigableMap<K,V> m) {
3017             super(m);
3018             nm = m;
3019         }
3020         SynchronizedNavigableMap(NavigableMap<K,V> m, Object mutex) {
3021             super(m, mutex);
3022             nm = m;
3023         }
3024 
3025         public Entry<K, V> lowerEntry(K key)
3026                         { synchronized (mutex) { return nm.lowerEntry(key); } }
3027         public K lowerKey(K key)
3028                           { synchronized (mutex) { return nm.lowerKey(key); } }
3029         public Entry<K, V> floorEntry(K key)
3030                         { synchronized (mutex) { return nm.floorEntry(key); } }
3031         public K floorKey(K key)
3032                           { synchronized (mutex) { return nm.floorKey(key); } }
3033         public Entry<K, V> ceilingEntry(K key)
3034                       { synchronized (mutex) { return nm.ceilingEntry(key); } }
3035         public K ceilingKey(K key)
3036                         { synchronized (mutex) { return nm.ceilingKey(key); } }
3037         public Entry<K, V> higherEntry(K key)
3038                        { synchronized (mutex) { return nm.higherEntry(key); } }
3039         public K higherKey(K key)
3040                          { synchronized (mutex) { return nm.higherKey(key); } }
3041         public Entry<K, V> firstEntry()
3042                            { synchronized (mutex) { return nm.firstEntry(); } }
3043         public Entry<K, V> lastEntry()
3044                             { synchronized (mutex) { return nm.lastEntry(); } }
3045         public Entry<K, V> pollFirstEntry()
3046                        { synchronized (mutex) { return nm.pollFirstEntry(); } }
3047         public Entry<K, V> pollLastEntry()
3048                         { synchronized (mutex) { return nm.pollLastEntry(); } }
3049 
3050         public NavigableMap<K, V> descendingMap() {
3051             synchronized (mutex) {
3052                 return
3053                     new SynchronizedNavigableMap<>(nm.descendingMap(), mutex);
3054             }
3055         }
3056 
3057         public NavigableSet<K> keySet() {
3058             return navigableKeySet();
3059         }
3060 
3061         public NavigableSet<K> navigableKeySet() {
3062             synchronized (mutex) {
3063                 return new SynchronizedNavigableSet<>(nm.navigableKeySet(), mutex);
3064             }
3065         }
3066 
3067         public NavigableSet<K> descendingKeySet() {
3068             synchronized (mutex) {
3069                 return new SynchronizedNavigableSet<>(nm.descendingKeySet(), mutex);
3070             }
3071         }
3072 
3073 
3074         public SortedMap<K,V> subMap(K fromKey, K toKey) {
3075             synchronized (mutex) {
3076                 return new SynchronizedNavigableMap<>(
3077                     nm.subMap(fromKey, true, toKey, false), mutex);
3078             }
3079         }
3080         public SortedMap<K,V> headMap(K toKey) {
3081             synchronized (mutex) {
3082                 return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex);
3083             }
3084         }
3085         public SortedMap<K,V> tailMap(K fromKey) {
3086             synchronized (mutex) {
3087         return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex);
3088             }
3089         }
3090 
3091         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
3092             synchronized (mutex) {
3093                 return new SynchronizedNavigableMap<>(
3094                     nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex);
3095             }
3096         }
3097 
3098         public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
3099             synchronized (mutex) {
3100                 return new SynchronizedNavigableMap<>(
3101                         nm.headMap(toKey, inclusive), mutex);
3102             }
3103         }
3104 
3105         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
3106             synchronized (mutex) {
3107                 return new SynchronizedNavigableMap<>(
3108                     nm.tailMap(fromKey, inclusive), mutex);
3109             }
3110         }
3111     }
3112 
3113     // Dynamically typesafe collection wrappers
3114 
3115     /**
3116      * Returns a dynamically typesafe view of the specified collection.
3117      * Any attempt to insert an element of the wrong type will result in an
3118      * immediate {@link ClassCastException}.  Assuming a collection
3119      * contains no incorrectly typed elements prior to the time a
3120      * dynamically typesafe view is generated, and that all subsequent
3121      * access to the collection takes place through the view, it is
3122      * <i>guaranteed</i> that the collection cannot contain an incorrectly
3123      * typed element.
3124      *
3125      * <p>The generics mechanism in the language provides compile-time
3126      * (static) type checking, but it is possible to defeat this mechanism
3127      * with unchecked casts.  Usually this is not a problem, as the compiler
3128      * issues warnings on all such unchecked operations.  There are, however,
3129      * times when static type checking alone is not sufficient.  For example,
3130      * suppose a collection is passed to a third-party library and it is
3131      * imperative that the library code not corrupt the collection by
3132      * inserting an element of the wrong type.
3133      *
3134      * <p>Another use of dynamically typesafe views is debugging.  Suppose a
3135      * program fails with a {@code ClassCastException}, indicating that an
3136      * incorrectly typed element was put into a parameterized collection.
3137      * Unfortunately, the exception can occur at any time after the erroneous
3138      * element is inserted, so it typically provides little or no information
3139      * as to the real source of the problem.  If the problem is reproducible,
3140      * one can quickly determine its source by temporarily modifying the
3141      * program to wrap the collection with a dynamically typesafe view.
3142      * For example, this declaration:
3143      *  <pre> {@code
3144      *     Collection<String> c = new HashSet<>();
3145      * }</pre>
3146      * may be replaced temporarily by this one:
3147      *  <pre> {@code
3148      *     Collection<String> c = Collections.checkedCollection(
3149      *         new HashSet<>(), String.class);
3150      * }</pre>
3151      * Running the program again will cause it to fail at the point where
3152      * an incorrectly typed element is inserted into the collection, clearly
3153      * identifying the source of the problem.  Once the problem is fixed, the
3154      * modified declaration may be reverted back to the original.
3155      *
3156      * <p>The returned collection does <i>not</i> pass the hashCode and equals
3157      * operations through to the backing collection, but relies on
3158      * {@code Object}'s {@code equals} and {@code hashCode} methods.  This
3159      * is necessary to preserve the contracts of these operations in the case
3160      * that the backing collection is a set or a list.
3161      *
3162      * <p>The returned collection will be serializable if the specified
3163      * collection is serializable.
3164      *
3165      * <p>Since {@code null} is considered to be a value of any reference
3166      * type, the returned collection permits insertion of null elements
3167      * whenever the backing collection does.
3168      *
3169      * @param <E> the class of the objects in the collection
3170      * @param c the collection for which a dynamically typesafe view is to be
3171      *          returned
3172      * @param type the type of element that {@code c} is permitted to hold
3173      * @return a dynamically typesafe view of the specified collection
3174      * @since 1.5
3175      */
3176     public static <E> Collection<E> checkedCollection(Collection<E> c,
3177                                                       Class<E> type) {
3178         return new CheckedCollection<>(c, type);
3179     }
3180 
3181     @SuppressWarnings("unchecked")
3182     static <T> T[] zeroLengthArray(Class<T> type) {
3183         return (T[]) Array.newInstance(type, 0);
3184     }
3185 
3186     /**
3187      * @serial include
3188      */
3189     static class CheckedCollection<E> implements Collection<E>, Serializable {
3190         @java.io.Serial
3191         private static final long serialVersionUID = 1578914078182001775L;
3192 
3193         @SuppressWarnings("serial") // Conditionally serializable
3194         final Collection<E> c;
3195         @SuppressWarnings("serial") // Conditionally serializable
3196         final Class<E> type;
3197 
3198         @SuppressWarnings("unchecked")
3199         E typeCheck(Object o) {
3200             if (o != null && !type.isInstance(o))
3201                 throw new ClassCastException(badElementMsg(o));
3202             return (E) o;
3203         }
3204 
3205         private String badElementMsg(Object o) {
3206             return "Attempt to insert " + o.getClass() +
3207                 " element into collection with element type " + type;
3208         }
3209 
3210         CheckedCollection(Collection<E> c, Class<E> type) {
3211             this.c = Objects.requireNonNull(c, "c");
3212             this.type = Objects.requireNonNull(type, "type");
3213         }
3214 
3215         public int size()                          { return c.size(); }
3216         public boolean isEmpty()                   { return c.isEmpty(); }
3217         public boolean contains(Object o)          { return c.contains(o); }
3218         public Object[] toArray()                  { return c.toArray(); }
3219         public <T> T[] toArray(T[] a)              { return c.toArray(a); }
3220         public <T> T[] toArray(IntFunction<T[]> f) { return c.toArray(f); }
3221         public String toString()                   { return c.toString(); }
3222         public boolean remove(Object o)            { return c.remove(o); }
3223         public void clear()                        {        c.clear(); }
3224 
3225         public boolean containsAll(Collection<?> coll) {
3226             return c.containsAll(coll);
3227         }
3228         public boolean removeAll(Collection<?> coll) {
3229             return c.removeAll(coll);
3230         }
3231         public boolean retainAll(Collection<?> coll) {
3232             return c.retainAll(coll);
3233         }
3234 
3235         public Iterator<E> iterator() {
3236             // JDK-6363904 - unwrapped iterator could be typecast to
3237             // ListIterator with unsafe set()
3238             final Iterator<E> it = c.iterator();
3239             return new Iterator<E>() {
3240                 public boolean hasNext() { return it.hasNext(); }
3241                 public E next()          { return it.next(); }
3242                 public void remove()     {        it.remove(); }
3243                 public void forEachRemaining(Consumer<? super E> action) {
3244                     it.forEachRemaining(action);
3245                 }
3246             };
3247         }
3248 
3249         public boolean add(E e)          { return c.add(typeCheck(e)); }
3250 
3251         @SuppressWarnings("serial") // Conditionally serializable
3252         private E[] zeroLengthElementArray; // Lazily initialized
3253 
3254         private E[] zeroLengthElementArray() {
3255             return zeroLengthElementArray != null ? zeroLengthElementArray :
3256                 (zeroLengthElementArray = zeroLengthArray(type));
3257         }
3258 
3259         @SuppressWarnings("unchecked")
3260         Collection<E> checkedCopyOf(Collection<? extends E> coll) {
3261             Object[] a;
3262             try {
3263                 E[] z = zeroLengthElementArray();
3264                 a = coll.toArray(z);
3265                 // Defend against coll violating the toArray contract
3266                 if (a.getClass() != z.getClass())
3267                     a = Arrays.copyOf(a, a.length, z.getClass());
3268             } catch (ArrayStoreException ignore) {
3269                 // To get better and consistent diagnostics,
3270                 // we call typeCheck explicitly on each element.
3271                 // We call clone() to defend against coll retaining a
3272                 // reference to the returned array and storing a bad
3273                 // element into it after it has been type checked.
3274                 a = coll.toArray().clone();
3275                 for (Object o : a)
3276                     typeCheck(o);
3277             }
3278             // A slight abuse of the type system, but safe here.
3279             return (Collection<E>) Arrays.asList(a);
3280         }
3281 
3282         public boolean addAll(Collection<? extends E> coll) {
3283             // Doing things this way insulates us from concurrent changes
3284             // in the contents of coll and provides all-or-nothing
3285             // semantics (which we wouldn't get if we type-checked each
3286             // element as we added it)
3287             return c.addAll(checkedCopyOf(coll));
3288         }
3289 
3290         // Override default methods in Collection
3291         @Override
3292         public void forEach(Consumer<? super E> action) {c.forEach(action);}
3293         @Override
3294         public boolean removeIf(Predicate<? super E> filter) {
3295             return c.removeIf(filter);
3296         }
3297         @Override
3298         public Spliterator<E> spliterator() {return c.spliterator();}
3299         @Override
3300         public Stream<E> stream()           {return c.stream();}
3301         @Override
3302         public Stream<E> parallelStream()   {return c.parallelStream();}
3303     }
3304 
3305     /**
3306      * Returns a dynamically typesafe view of the specified queue.
3307      * Any attempt to insert an element of the wrong type will result in
3308      * an immediate {@link ClassCastException}.  Assuming a queue contains
3309      * no incorrectly typed elements prior to the time a dynamically typesafe
3310      * view is generated, and that all subsequent access to the queue
3311      * takes place through the view, it is <i>guaranteed</i> that the
3312      * queue cannot contain an incorrectly typed element.
3313      *
3314      * <p>A discussion of the use of dynamically typesafe views may be
3315      * found in the documentation for the {@link #checkedCollection
3316      * checkedCollection} method.
3317      *
3318      * <p>The returned queue will be serializable if the specified queue
3319      * is serializable.
3320      *
3321      * <p>Since {@code null} is considered to be a value of any reference
3322      * type, the returned queue permits insertion of {@code null} elements
3323      * whenever the backing queue does.
3324      *
3325      * @param <E> the class of the objects in the queue
3326      * @param queue the queue for which a dynamically typesafe view is to be
3327      *             returned
3328      * @param type the type of element that {@code queue} is permitted to hold
3329      * @return a dynamically typesafe view of the specified queue
3330      * @since 1.8
3331      */
3332     public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type) {
3333         return new CheckedQueue<>(queue, type);
3334     }
3335 
3336     /**
3337      * @serial include
3338      */
3339     static class CheckedQueue<E>
3340         extends CheckedCollection<E>
3341         implements Queue<E>, Serializable
3342     {
3343         @java.io.Serial
3344         private static final long serialVersionUID = 1433151992604707767L;
3345         @SuppressWarnings("serial") // Conditionally serializable
3346         final Queue<E> queue;
3347 
3348         CheckedQueue(Queue<E> queue, Class<E> elementType) {
3349             super(queue, elementType);
3350             this.queue = queue;
3351         }
3352 
3353         public E element()              {return queue.element();}
3354         public boolean equals(Object o) {return o == this || c.equals(o);}
3355         public int hashCode()           {return c.hashCode();}
3356         public E peek()                 {return queue.peek();}
3357         public E poll()                 {return queue.poll();}
3358         public E remove()               {return queue.remove();}
3359         public boolean offer(E e)       {return queue.offer(typeCheck(e));}
3360     }
3361 
3362     /**
3363      * Returns a dynamically typesafe view of the specified set.
3364      * Any attempt to insert an element of the wrong type will result in
3365      * an immediate {@link ClassCastException}.  Assuming a set contains
3366      * no incorrectly typed elements prior to the time a dynamically typesafe
3367      * view is generated, and that all subsequent access to the set
3368      * takes place through the view, it is <i>guaranteed</i> that the
3369      * set cannot contain an incorrectly typed element.
3370      *
3371      * <p>A discussion of the use of dynamically typesafe views may be
3372      * found in the documentation for the {@link #checkedCollection
3373      * checkedCollection} method.
3374      *
3375      * <p>The returned set will be serializable if the specified set is
3376      * serializable.
3377      *
3378      * <p>Since {@code null} is considered to be a value of any reference
3379      * type, the returned set permits insertion of null elements whenever
3380      * the backing set does.
3381      *
3382      * @param <E> the class of the objects in the set
3383      * @param s the set for which a dynamically typesafe view is to be
3384      *          returned
3385      * @param type the type of element that {@code s} is permitted to hold
3386      * @return a dynamically typesafe view of the specified set
3387      * @since 1.5
3388      */
3389     public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
3390         return new CheckedSet<>(s, type);
3391     }
3392 
3393     /**
3394      * @serial include
3395      */
3396     static class CheckedSet<E> extends CheckedCollection<E>
3397                                  implements Set<E>, Serializable
3398     {
3399         @java.io.Serial
3400         private static final long serialVersionUID = 4694047833775013803L;
3401 
3402         CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
3403 
3404         public boolean equals(Object o) { return o == this || c.equals(o); }
3405         public int hashCode()           { return c.hashCode(); }
3406     }
3407 
3408     /**
3409      * Returns a dynamically typesafe view of the specified sorted set.
3410      * Any attempt to insert an element of the wrong type will result in an
3411      * immediate {@link ClassCastException}.  Assuming a sorted set
3412      * contains no incorrectly typed elements prior to the time a
3413      * dynamically typesafe view is generated, and that all subsequent
3414      * access to the sorted set takes place through the view, it is
3415      * <i>guaranteed</i> that the sorted set cannot contain an incorrectly
3416      * typed element.
3417      *
3418      * <p>A discussion of the use of dynamically typesafe views may be
3419      * found in the documentation for the {@link #checkedCollection
3420      * checkedCollection} method.
3421      *
3422      * <p>The returned sorted set will be serializable if the specified sorted
3423      * set is serializable.
3424      *
3425      * <p>Since {@code null} is considered to be a value of any reference
3426      * type, the returned sorted set permits insertion of null elements
3427      * whenever the backing sorted set does.
3428      *
3429      * @param <E> the class of the objects in the set
3430      * @param s the sorted set for which a dynamically typesafe view is to be
3431      *          returned
3432      * @param type the type of element that {@code s} is permitted to hold
3433      * @return a dynamically typesafe view of the specified sorted set
3434      * @since 1.5
3435      */
3436     public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
3437                                                     Class<E> type) {
3438         return new CheckedSortedSet<>(s, type);
3439     }
3440 
3441     /**
3442      * @serial include
3443      */
3444     static class CheckedSortedSet<E> extends CheckedSet<E>
3445         implements SortedSet<E>, Serializable
3446     {
3447         @java.io.Serial
3448         private static final long serialVersionUID = 1599911165492914959L;
3449 
3450         @SuppressWarnings("serial") // Conditionally serializable
3451         private final SortedSet<E> ss;
3452 
3453         CheckedSortedSet(SortedSet<E> s, Class<E> type) {
3454             super(s, type);
3455             ss = s;
3456         }
3457 
3458         public Comparator<? super E> comparator() { return ss.comparator(); }
3459         public E first()                   { return ss.first(); }
3460         public E last()                    { return ss.last(); }
3461 
3462         public SortedSet<E> subSet(E fromElement, E toElement) {
3463             return checkedSortedSet(ss.subSet(fromElement,toElement), type);
3464         }
3465         public SortedSet<E> headSet(E toElement) {
3466             return checkedSortedSet(ss.headSet(toElement), type);
3467         }
3468         public SortedSet<E> tailSet(E fromElement) {
3469             return checkedSortedSet(ss.tailSet(fromElement), type);
3470         }
3471     }
3472 
3473     /**
3474      * Returns a dynamically typesafe view of the specified navigable set.
3475      * Any attempt to insert an element of the wrong type will result in an
3476      * immediate {@link ClassCastException}.  Assuming a navigable set
3477      * contains no incorrectly typed elements prior to the time a
3478      * dynamically typesafe view is generated, and that all subsequent
3479      * access to the navigable set takes place through the view, it is
3480      * <em>guaranteed</em> that the navigable set cannot contain an incorrectly
3481      * typed element.
3482      *
3483      * <p>A discussion of the use of dynamically typesafe views may be
3484      * found in the documentation for the {@link #checkedCollection
3485      * checkedCollection} method.
3486      *
3487      * <p>The returned navigable set will be serializable if the specified
3488      * navigable set is serializable.
3489      *
3490      * <p>Since {@code null} is considered to be a value of any reference
3491      * type, the returned navigable set permits insertion of null elements
3492      * whenever the backing sorted set does.
3493      *
3494      * @param <E> the class of the objects in the set
3495      * @param s the navigable set for which a dynamically typesafe view is to be
3496      *          returned
3497      * @param type the type of element that {@code s} is permitted to hold
3498      * @return a dynamically typesafe view of the specified navigable set
3499      * @since 1.8
3500      */
3501     public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s,
3502                                                     Class<E> type) {
3503         return new CheckedNavigableSet<>(s, type);
3504     }
3505 
3506     /**
3507      * @serial include
3508      */
3509     static class CheckedNavigableSet<E> extends CheckedSortedSet<E>
3510         implements NavigableSet<E>, Serializable
3511     {
3512         @java.io.Serial
3513         private static final long serialVersionUID = -5429120189805438922L;
3514 
3515         @SuppressWarnings("serial") // Conditionally serializable
3516         private final NavigableSet<E> ns;
3517 
3518         CheckedNavigableSet(NavigableSet<E> s, Class<E> type) {
3519             super(s, type);
3520             ns = s;
3521         }
3522 
3523         public E lower(E e)                             { return ns.lower(e); }
3524         public E floor(E e)                             { return ns.floor(e); }
3525         public E ceiling(E e)                         { return ns.ceiling(e); }
3526         public E higher(E e)                           { return ns.higher(e); }
3527         public E pollFirst()                         { return ns.pollFirst(); }
3528         public E pollLast()                            {return ns.pollLast(); }
3529         public NavigableSet<E> descendingSet()
3530                       { return checkedNavigableSet(ns.descendingSet(), type); }
3531         public Iterator<E> descendingIterator()
3532             {return checkedNavigableSet(ns.descendingSet(), type).iterator(); }
3533 
3534         public NavigableSet<E> subSet(E fromElement, E toElement) {
3535             return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type);
3536         }
3537         public NavigableSet<E> headSet(E toElement) {
3538             return checkedNavigableSet(ns.headSet(toElement, false), type);
3539         }
3540         public NavigableSet<E> tailSet(E fromElement) {
3541             return checkedNavigableSet(ns.tailSet(fromElement, true), type);
3542         }
3543 
3544         public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
3545             return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type);
3546         }
3547 
3548         public NavigableSet<E> headSet(E toElement, boolean inclusive) {
3549             return checkedNavigableSet(ns.headSet(toElement, inclusive), type);
3550         }
3551 
3552         public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
3553             return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type);
3554         }
3555     }
3556 
3557     /**
3558      * Returns a dynamically typesafe view of the specified list.
3559      * Any attempt to insert an element of the wrong type will result in
3560      * an immediate {@link ClassCastException}.  Assuming a list contains
3561      * no incorrectly typed elements prior to the time a dynamically typesafe
3562      * view is generated, and that all subsequent access to the list
3563      * takes place through the view, it is <i>guaranteed</i> that the
3564      * list cannot contain an incorrectly typed element.
3565      *
3566      * <p>A discussion of the use of dynamically typesafe views may be
3567      * found in the documentation for the {@link #checkedCollection
3568      * checkedCollection} method.
3569      *
3570      * <p>The returned list will be serializable if the specified list
3571      * is serializable.
3572      *
3573      * <p>Since {@code null} is considered to be a value of any reference
3574      * type, the returned list permits insertion of null elements whenever
3575      * the backing list does.
3576      *
3577      * @param <E> the class of the objects in the list
3578      * @param list the list for which a dynamically typesafe view is to be
3579      *             returned
3580      * @param type the type of element that {@code list} is permitted to hold
3581      * @return a dynamically typesafe view of the specified list
3582      * @since 1.5
3583      */
3584     public static <E> List<E> checkedList(List<E> list, Class<E> type) {
3585         return (list instanceof RandomAccess ?
3586                 new CheckedRandomAccessList<>(list, type) :
3587                 new CheckedList<>(list, type));
3588     }
3589 
3590     /**
3591      * @serial include
3592      */
3593     static class CheckedList<E>
3594         extends CheckedCollection<E>
3595         implements List<E>
3596     {
3597         @java.io.Serial
3598         private static final long serialVersionUID = 65247728283967356L;
3599         @SuppressWarnings("serial") // Conditionally serializable
3600         final List<E> list;
3601 
3602         CheckedList(List<E> list, Class<E> type) {
3603             super(list, type);
3604             this.list = list;
3605         }
3606 
3607         public boolean equals(Object o)  { return o == this || list.equals(o); }
3608         public int hashCode()            { return list.hashCode(); }
3609         public E get(int index)          { return list.get(index); }
3610         public E remove(int index)       { return list.remove(index); }
3611         public int indexOf(Object o)     { return list.indexOf(o); }
3612         public int lastIndexOf(Object o) { return list.lastIndexOf(o); }
3613 
3614         public E set(int index, E element) {
3615             return list.set(index, typeCheck(element));
3616         }
3617 
3618         public void add(int index, E element) {
3619             list.add(index, typeCheck(element));
3620         }
3621 
3622         public boolean addAll(int index, Collection<? extends E> c) {
3623             return list.addAll(index, checkedCopyOf(c));
3624         }
3625         public ListIterator<E> listIterator()   { return listIterator(0); }
3626 
3627         public ListIterator<E> listIterator(final int index) {
3628             final ListIterator<E> i = list.listIterator(index);
3629 
3630             return new ListIterator<E>() {
3631                 public boolean hasNext()     { return i.hasNext(); }
3632                 public E next()              { return i.next(); }
3633                 public boolean hasPrevious() { return i.hasPrevious(); }
3634                 public E previous()          { return i.previous(); }
3635                 public int nextIndex()       { return i.nextIndex(); }
3636                 public int previousIndex()   { return i.previousIndex(); }
3637                 public void remove()         {        i.remove(); }
3638 
3639                 public void set(E e) {
3640                     i.set(typeCheck(e));
3641                 }
3642 
3643                 public void add(E e) {
3644                     i.add(typeCheck(e));
3645                 }
3646 
3647                 @Override
3648                 public void forEachRemaining(Consumer<? super E> action) {
3649                     i.forEachRemaining(action);
3650                 }
3651             };
3652         }
3653 
3654         public List<E> subList(int fromIndex, int toIndex) {
3655             return new CheckedList<>(list.subList(fromIndex, toIndex), type);
3656         }
3657 
3658         /**
3659          * {@inheritDoc}
3660          *
3661          * @throws ClassCastException if the class of an element returned by the
3662          *         operator prevents it from being added to this collection. The
3663          *         exception may be thrown after some elements of the list have
3664          *         already been replaced.
3665          */
3666         @Override
3667         public void replaceAll(UnaryOperator<E> operator) {
3668             Objects.requireNonNull(operator);
3669             list.replaceAll(e -> typeCheck(operator.apply(e)));
3670         }
3671 
3672         @Override
3673         public void sort(Comparator<? super E> c) {
3674             list.sort(c);
3675         }
3676     }
3677 
3678     /**
3679      * @serial include
3680      */
3681     static class CheckedRandomAccessList<E> extends CheckedList<E>
3682                                             implements RandomAccess
3683     {
3684         @java.io.Serial
3685         private static final long serialVersionUID = 1638200125423088369L;
3686 
3687         CheckedRandomAccessList(List<E> list, Class<E> type) {
3688             super(list, type);
3689         }
3690 
3691         public List<E> subList(int fromIndex, int toIndex) {
3692             return new CheckedRandomAccessList<>(
3693                     list.subList(fromIndex, toIndex), type);
3694         }
3695     }
3696 
3697     /**
3698      * Returns a dynamically typesafe view of the specified map.
3699      * Any attempt to insert a mapping whose key or value have the wrong
3700      * type will result in an immediate {@link ClassCastException}.
3701      * Similarly, any attempt to modify the value currently associated with
3702      * a key will result in an immediate {@link ClassCastException},
3703      * whether the modification is attempted directly through the map
3704      * itself, or through a {@link Map.Entry} instance obtained from the
3705      * map's {@link Map#entrySet() entry set} view.
3706      *
3707      * <p>Assuming a map contains no incorrectly typed keys or values
3708      * prior to the time a dynamically typesafe view is generated, and
3709      * that all subsequent access to the map takes place through the view
3710      * (or one of its collection views), it is <i>guaranteed</i> that the
3711      * map cannot contain an incorrectly typed key or value.
3712      *
3713      * <p>A discussion of the use of dynamically typesafe views may be
3714      * found in the documentation for the {@link #checkedCollection
3715      * checkedCollection} method.
3716      *
3717      * <p>The returned map will be serializable if the specified map is
3718      * serializable.
3719      *
3720      * <p>Since {@code null} is considered to be a value of any reference
3721      * type, the returned map permits insertion of null keys or values
3722      * whenever the backing map does.
3723      *
3724      * @param <K> the class of the map keys
3725      * @param <V> the class of the map values
3726      * @param m the map for which a dynamically typesafe view is to be
3727      *          returned
3728      * @param keyType the type of key that {@code m} is permitted to hold
3729      * @param valueType the type of value that {@code m} is permitted to hold
3730      * @return a dynamically typesafe view of the specified map
3731      * @since 1.5
3732      */
3733     public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
3734                                               Class<K> keyType,
3735                                               Class<V> valueType) {
3736         return new CheckedMap<>(m, keyType, valueType);
3737     }
3738 
3739 
3740     /**
3741      * @serial include
3742      */
3743     private static class CheckedMap<K,V>
3744         implements Map<K,V>, Serializable
3745     {
3746         @java.io.Serial
3747         private static final long serialVersionUID = 5742860141034234728L;
3748 
3749         @SuppressWarnings("serial") // Conditionally serializable
3750         private final Map<K, V> m;
3751         @SuppressWarnings("serial") // Conditionally serializable
3752         final Class<K> keyType;
3753         @SuppressWarnings("serial") // Conditionally serializable
3754         final Class<V> valueType;
3755 
3756         private void typeCheck(Object key, Object value) {
3757             if (key != null && !keyType.isInstance(key))
3758                 throw new ClassCastException(badKeyMsg(key));
3759 
3760             if (value != null && !valueType.isInstance(value))
3761                 throw new ClassCastException(badValueMsg(value));
3762         }
3763 
3764         private BiFunction<? super K, ? super V, ? extends V> typeCheck(
3765                 BiFunction<? super K, ? super V, ? extends V> func) {
3766             Objects.requireNonNull(func);
3767             return (k, v) -> {
3768                 V newValue = func.apply(k, v);
3769                 typeCheck(k, newValue);
3770                 return newValue;
3771             };
3772         }
3773 
3774         private String badKeyMsg(Object key) {
3775             return "Attempt to insert " + key.getClass() +
3776                     " key into map with key type " + keyType;
3777         }
3778 
3779         private String badValueMsg(Object value) {
3780             return "Attempt to insert " + value.getClass() +
3781                     " value into map with value type " + valueType;
3782         }
3783 
3784         CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
3785             this.m = Objects.requireNonNull(m);
3786             this.keyType = Objects.requireNonNull(keyType);
3787             this.valueType = Objects.requireNonNull(valueType);
3788         }
3789 
3790         public int size()                      { return m.size(); }
3791         public boolean isEmpty()               { return m.isEmpty(); }
3792         public boolean containsKey(Object key) { return m.containsKey(key); }
3793         public boolean containsValue(Object v) { return m.containsValue(v); }
3794         public V get(Object key)               { return m.get(key); }
3795         public V remove(Object key)            { return m.remove(key); }
3796         public void clear()                    { m.clear(); }
3797         public Set<K> keySet()                 { return m.keySet(); }
3798         public Collection<V> values()          { return m.values(); }
3799         public boolean equals(Object o)        { return o == this || m.equals(o); }
3800         public int hashCode()                  { return m.hashCode(); }
3801         public String toString()               { return m.toString(); }
3802 
3803         public V put(K key, V value) {
3804             typeCheck(key, value);
3805             return m.put(key, value);
3806         }
3807 
3808         @SuppressWarnings("unchecked")
3809         public void putAll(Map<? extends K, ? extends V> t) {
3810             // Satisfy the following goals:
3811             // - good diagnostics in case of type mismatch
3812             // - all-or-nothing semantics
3813             // - protection from malicious t
3814             // - correct behavior if t is a concurrent map
3815             Object[] entries = t.entrySet().toArray();
3816             List<Map.Entry<K,V>> checked = new ArrayList<>(entries.length);
3817             for (Object o : entries) {
3818                 Map.Entry<?,?> e = (Map.Entry<?,?>) o;
3819                 Object k = e.getKey();
3820                 Object v = e.getValue();
3821                 typeCheck(k, v);
3822                 checked.add(
3823                         new AbstractMap.SimpleImmutableEntry<>((K)k, (V)v));
3824             }
3825             for (Map.Entry<K,V> e : checked)
3826                 m.put(e.getKey(), e.getValue());
3827         }
3828 
3829         private transient Set<Map.Entry<K,V>> entrySet;
3830 
3831         public Set<Map.Entry<K,V>> entrySet() {
3832             if (entrySet==null)
3833                 entrySet = new CheckedEntrySet<>(m.entrySet(), valueType);
3834             return entrySet;
3835         }
3836 
3837         // Override default methods in Map
3838         @Override
3839         public void forEach(BiConsumer<? super K, ? super V> action) {
3840             m.forEach(action);
3841         }
3842 
3843         @Override
3844         public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3845             m.replaceAll(typeCheck(function));
3846         }
3847 
3848         @Override
3849         public V putIfAbsent(K key, V value) {
3850             typeCheck(key, value);
3851             return m.putIfAbsent(key, value);
3852         }
3853 
3854         @Override
3855         public boolean remove(Object key, Object value) {
3856             return m.remove(key, value);
3857         }
3858 
3859         @Override
3860         public boolean replace(K key, V oldValue, V newValue) {
3861             typeCheck(key, newValue);
3862             return m.replace(key, oldValue, newValue);
3863         }
3864 
3865         @Override
3866         public V replace(K key, V value) {
3867             typeCheck(key, value);
3868             return m.replace(key, value);
3869         }
3870 
3871         @Override
3872         public V computeIfAbsent(K key,
3873                 Function<? super K, ? extends V> mappingFunction) {
3874             Objects.requireNonNull(mappingFunction);
3875             return m.computeIfAbsent(key, k -> {
3876                 V value = mappingFunction.apply(k);
3877                 typeCheck(k, value);
3878                 return value;
3879             });
3880         }
3881 
3882         @Override
3883         public V computeIfPresent(K key,
3884                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
3885             return m.computeIfPresent(key, typeCheck(remappingFunction));
3886         }
3887 
3888         @Override
3889         public V compute(K key,
3890                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
3891             return m.compute(key, typeCheck(remappingFunction));
3892         }
3893 
3894         @Override
3895         public V merge(K key, V value,
3896                 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
3897             Objects.requireNonNull(remappingFunction);
3898             return m.merge(key, value, (v1, v2) -> {
3899                 V newValue = remappingFunction.apply(v1, v2);
3900                 typeCheck(null, newValue);
3901                 return newValue;
3902             });
3903         }
3904 
3905         /**
3906          * We need this class in addition to CheckedSet as Map.Entry permits
3907          * modification of the backing Map via the setValue operation.  This
3908          * class is subtle: there are many possible attacks that must be
3909          * thwarted.
3910          *
3911          * @serial exclude
3912          */
3913         static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {
3914             private final Set<Map.Entry<K,V>> s;
3915             private final Class<V> valueType;
3916 
3917             CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {
3918                 this.s = s;
3919                 this.valueType = valueType;
3920             }
3921 
3922             public int size()        { return s.size(); }
3923             public boolean isEmpty() { return s.isEmpty(); }
3924             public String toString() { return s.toString(); }
3925             public int hashCode()    { return s.hashCode(); }
3926             public void clear()      {        s.clear(); }
3927 
3928             public boolean add(Map.Entry<K, V> e) {
3929                 throw new UnsupportedOperationException();
3930             }
3931             public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {
3932                 throw new UnsupportedOperationException();
3933             }
3934 
3935             public Iterator<Map.Entry<K,V>> iterator() {
3936                 final Iterator<Map.Entry<K, V>> i = s.iterator();
3937 
3938                 return new Iterator<Map.Entry<K,V>>() {
3939                     public boolean hasNext() { return i.hasNext(); }
3940                     public void remove()     { i.remove(); }
3941 
3942                     public Map.Entry<K,V> next() {
3943                         return checkedEntry(i.next(), valueType);
3944                     }
3945                     public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
3946                         i.forEachRemaining(
3947                             e -> action.accept(checkedEntry(e, valueType)));
3948                     }
3949                 };
3950             }
3951 
3952             // Android-changed: Ignore IsInstanceOfClass warning. b/73288967, b/73344263.
3953             // @SuppressWarnings("unchecked")
3954             @SuppressWarnings({ "unchecked", "IsInstanceOfClass" })
3955             public Object[] toArray() {
3956                 Object[] source = s.toArray();
3957 
3958                 /*
3959                  * Ensure that we don't get an ArrayStoreException even if
3960                  * s.toArray returns an array of something other than Object
3961                  */
3962                 Object[] dest = (source.getClass() == Object[].class)
3963                     ? source
3964                     : new Object[source.length];
3965 
3966                 for (int i = 0; i < source.length; i++)
3967                     dest[i] = checkedEntry((Map.Entry<K,V>)source[i],
3968                                            valueType);
3969                 return dest;
3970             }
3971 
3972             @SuppressWarnings("unchecked")
3973             public <T> T[] toArray(T[] a) {
3974                 // We don't pass a to s.toArray, to avoid window of
3975                 // vulnerability wherein an unscrupulous multithreaded client
3976                 // could get his hands on raw (unwrapped) Entries from s.
3977                 T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
3978 
3979                 for (int i=0; i<arr.length; i++)
3980                     arr[i] = (T) checkedEntry((Map.Entry<K,V>)arr[i],
3981                                               valueType);
3982                 if (arr.length > a.length)
3983                     return arr;
3984 
3985                 System.arraycopy(arr, 0, a, 0, arr.length);
3986                 if (a.length > arr.length)
3987                     a[arr.length] = null;
3988                 return a;
3989             }
3990 
3991             /**
3992              * This method is overridden to protect the backing set against
3993              * an object with a nefarious equals function that senses
3994              * that the equality-candidate is Map.Entry and calls its
3995              * setValue method.
3996              */
3997             public boolean contains(Object o) {
3998                 // Android-changed: (b/247094511) instanceof pattern variable is not yet supported.
3999                 /*
4000                 return o instanceof Map.Entry<?, ?> e
4001                         && s.contains((e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));
4002                  */
4003                 if (!(o instanceof Map.Entry))
4004                     return false;
4005                 Map.Entry<?,?> e = (Map.Entry<?,?>) o;
4006                 return s.contains(
4007                         (e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));
4008             }
4009 
4010             /**
4011              * The bulk collection methods are overridden to protect
4012              * against an unscrupulous collection whose contains(Object o)
4013              * method senses when o is a Map.Entry, and calls o.setValue.
4014              */
4015             public boolean containsAll(Collection<?> c) {
4016                 for (Object o : c)
4017                     if (!contains(o)) // Invokes safe contains() above
4018                         return false;
4019                 return true;
4020             }
4021 
4022             public boolean remove(Object o) {
4023                 if (!(o instanceof Map.Entry))
4024                     return false;
4025                 return s.remove(new AbstractMap.SimpleImmutableEntry
4026                                 <>((Map.Entry<?,?>)o));
4027             }
4028 
4029             public boolean removeAll(Collection<?> c) {
4030                 return batchRemove(c, false);
4031             }
4032             public boolean retainAll(Collection<?> c) {
4033                 return batchRemove(c, true);
4034             }
4035             private boolean batchRemove(Collection<?> c, boolean complement) {
4036                 Objects.requireNonNull(c);
4037                 boolean modified = false;
4038                 Iterator<Map.Entry<K,V>> it = iterator();
4039                 while (it.hasNext()) {
4040                     if (c.contains(it.next()) != complement) {
4041                         it.remove();
4042                         modified = true;
4043                     }
4044                 }
4045                 return modified;
4046             }
4047 
4048             public boolean equals(Object o) {
4049                 if (o == this)
4050                     return true;
4051                 // Android-changed: (b/247094511) instanceof pattern variable is not yet supported
4052                 /*
4053                 return o instanceof Set<?> that
4054                         && that.size() == s.size()
4055                         && containsAll(that); // Invokes safe containsAll() above
4056                  */
4057                 if (!(o instanceof Set))
4058                     return false;
4059                 Set<?> that = (Set<?>) o;
4060                 return that.size() == s.size()
4061                         && containsAll(that); // Invokes safe containsAll() above
4062             }
4063 
4064             static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,
4065                                                             Class<T> valueType) {
4066                 return new CheckedEntry<>(e, valueType);
4067             }
4068 
4069             /**
4070              * This "wrapper class" serves two purposes: it prevents
4071              * the client from modifying the backing Map, by short-circuiting
4072              * the setValue method, and it protects the backing Map against
4073              * an ill-behaved Map.Entry that attempts to modify another
4074              * Map.Entry when asked to perform an equality check.
4075              */
4076             private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {
4077                 private final Map.Entry<K, V> e;
4078                 private final Class<T> valueType;
4079 
4080                 CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
4081                     this.e = Objects.requireNonNull(e);
4082                     this.valueType = Objects.requireNonNull(valueType);
4083                 }
4084 
4085                 public K getKey()        { return e.getKey(); }
4086                 public V getValue()      { return e.getValue(); }
4087                 public int hashCode()    { return e.hashCode(); }
4088                 public String toString() { return e.toString(); }
4089 
4090                 public V setValue(V value) {
4091                     if (value != null && !valueType.isInstance(value))
4092                         throw new ClassCastException(badValueMsg(value));
4093                     return e.setValue(value);
4094                 }
4095 
4096                 private String badValueMsg(Object value) {
4097                     return "Attempt to insert " + value.getClass() +
4098                         " value into map with value type " + valueType;
4099                 }
4100 
4101                 public boolean equals(Object o) {
4102                     if (o == this)
4103                         return true;
4104                     if (!(o instanceof Map.Entry))
4105                         return false;
4106                     return e.equals(new AbstractMap.SimpleImmutableEntry
4107                                     <>((Map.Entry<?,?>)o));
4108                 }
4109             }
4110         }
4111     }
4112 
4113     /**
4114      * Returns a dynamically typesafe view of the specified sorted map.
4115      * Any attempt to insert a mapping whose key or value have the wrong
4116      * type will result in an immediate {@link ClassCastException}.
4117      * Similarly, any attempt to modify the value currently associated with
4118      * a key will result in an immediate {@link ClassCastException},
4119      * whether the modification is attempted directly through the map
4120      * itself, or through a {@link Map.Entry} instance obtained from the
4121      * map's {@link Map#entrySet() entry set} view.
4122      *
4123      * <p>Assuming a map contains no incorrectly typed keys or values
4124      * prior to the time a dynamically typesafe view is generated, and
4125      * that all subsequent access to the map takes place through the view
4126      * (or one of its collection views), it is <i>guaranteed</i> that the
4127      * map cannot contain an incorrectly typed key or value.
4128      *
4129      * <p>A discussion of the use of dynamically typesafe views may be
4130      * found in the documentation for the {@link #checkedCollection
4131      * checkedCollection} method.
4132      *
4133      * <p>The returned map will be serializable if the specified map is
4134      * serializable.
4135      *
4136      * <p>Since {@code null} is considered to be a value of any reference
4137      * type, the returned map permits insertion of null keys or values
4138      * whenever the backing map does.
4139      *
4140      * @param <K> the class of the map keys
4141      * @param <V> the class of the map values
4142      * @param m the map for which a dynamically typesafe view is to be
4143      *          returned
4144      * @param keyType the type of key that {@code m} is permitted to hold
4145      * @param valueType the type of value that {@code m} is permitted to hold
4146      * @return a dynamically typesafe view of the specified map
4147      * @since 1.5
4148      */
4149     public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
4150                                                         Class<K> keyType,
4151                                                         Class<V> valueType) {
4152         return new CheckedSortedMap<>(m, keyType, valueType);
4153     }
4154 
4155     /**
4156      * @serial include
4157      */
4158     static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
4159         implements SortedMap<K,V>, Serializable
4160     {
4161         @java.io.Serial
4162         private static final long serialVersionUID = 1599671320688067438L;
4163 
4164         @SuppressWarnings("serial") // Conditionally serializable
4165         private final SortedMap<K, V> sm;
4166 
4167         CheckedSortedMap(SortedMap<K, V> m,
4168                          Class<K> keyType, Class<V> valueType) {
4169             super(m, keyType, valueType);
4170             sm = m;
4171         }
4172 
4173         public Comparator<? super K> comparator() { return sm.comparator(); }
4174         public K firstKey()                       { return sm.firstKey(); }
4175         public K lastKey()                        { return sm.lastKey(); }
4176 
4177         public SortedMap<K,V> subMap(K fromKey, K toKey) {
4178             return checkedSortedMap(sm.subMap(fromKey, toKey),
4179                                     keyType, valueType);
4180         }
4181         public SortedMap<K,V> headMap(K toKey) {
4182             return checkedSortedMap(sm.headMap(toKey), keyType, valueType);
4183         }
4184         public SortedMap<K,V> tailMap(K fromKey) {
4185             return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);
4186         }
4187     }
4188 
4189     /**
4190      * Returns a dynamically typesafe view of the specified navigable map.
4191      * Any attempt to insert a mapping whose key or value have the wrong
4192      * type will result in an immediate {@link ClassCastException}.
4193      * Similarly, any attempt to modify the value currently associated with
4194      * a key will result in an immediate {@link ClassCastException},
4195      * whether the modification is attempted directly through the map
4196      * itself, or through a {@link Map.Entry} instance obtained from the
4197      * map's {@link Map#entrySet() entry set} view.
4198      *
4199      * <p>Assuming a map contains no incorrectly typed keys or values
4200      * prior to the time a dynamically typesafe view is generated, and
4201      * that all subsequent access to the map takes place through the view
4202      * (or one of its collection views), it is <em>guaranteed</em> that the
4203      * map cannot contain an incorrectly typed key or value.
4204      *
4205      * <p>A discussion of the use of dynamically typesafe views may be
4206      * found in the documentation for the {@link #checkedCollection
4207      * checkedCollection} method.
4208      *
4209      * <p>The returned map will be serializable if the specified map is
4210      * serializable.
4211      *
4212      * <p>Since {@code null} is considered to be a value of any reference
4213      * type, the returned map permits insertion of null keys or values
4214      * whenever the backing map does.
4215      *
4216      * @param <K> type of map keys
4217      * @param <V> type of map values
4218      * @param m the map for which a dynamically typesafe view is to be
4219      *          returned
4220      * @param keyType the type of key that {@code m} is permitted to hold
4221      * @param valueType the type of value that {@code m} is permitted to hold
4222      * @return a dynamically typesafe view of the specified map
4223      * @since 1.8
4224      */
4225     public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K, V> m,
4226                                                         Class<K> keyType,
4227                                                         Class<V> valueType) {
4228         return new CheckedNavigableMap<>(m, keyType, valueType);
4229     }
4230 
4231     /**
4232      * @serial include
4233      */
4234     static class CheckedNavigableMap<K,V> extends CheckedSortedMap<K,V>
4235         implements NavigableMap<K,V>, Serializable
4236     {
4237         @java.io.Serial
4238         private static final long serialVersionUID = -4852462692372534096L;
4239 
4240         @SuppressWarnings("serial") // Conditionally serializable
4241         private final NavigableMap<K, V> nm;
4242 
4243         CheckedNavigableMap(NavigableMap<K, V> m,
4244                          Class<K> keyType, Class<V> valueType) {
4245             super(m, keyType, valueType);
4246             nm = m;
4247         }
4248 
4249         public Comparator<? super K> comparator()   { return nm.comparator(); }
4250         public K firstKey()                           { return nm.firstKey(); }
4251         public K lastKey()                             { return nm.lastKey(); }
4252 
4253         public Entry<K, V> lowerEntry(K key) {
4254             Entry<K,V> lower = nm.lowerEntry(key);
4255             return (null != lower)
4256                 ? new CheckedMap.CheckedEntrySet.CheckedEntry<>(lower, valueType)
4257                 : null;
4258         }
4259 
4260         public K lowerKey(K key)                   { return nm.lowerKey(key); }
4261 
4262         public Entry<K, V> floorEntry(K key) {
4263             Entry<K,V> floor = nm.floorEntry(key);
4264             return (null != floor)
4265                 ? new CheckedMap.CheckedEntrySet.CheckedEntry<>(floor, valueType)
4266                 : null;
4267         }
4268 
4269         public K floorKey(K key)                   { return nm.floorKey(key); }
4270 
4271         public Entry<K, V> ceilingEntry(K key) {
4272             Entry<K,V> ceiling = nm.ceilingEntry(key);
4273             return (null != ceiling)
4274                 ? new CheckedMap.CheckedEntrySet.CheckedEntry<>(ceiling, valueType)
4275                 : null;
4276         }
4277 
4278         public K ceilingKey(K key)               { return nm.ceilingKey(key); }
4279 
4280         public Entry<K, V> higherEntry(K key) {
4281             Entry<K,V> higher = nm.higherEntry(key);
4282             return (null != higher)
4283                 ? new CheckedMap.CheckedEntrySet.CheckedEntry<>(higher, valueType)
4284                 : null;
4285         }
4286 
4287         public K higherKey(K key)                 { return nm.higherKey(key); }
4288 
4289         public Entry<K, V> firstEntry() {
4290             Entry<K,V> first = nm.firstEntry();
4291             return (null != first)
4292                 ? new CheckedMap.CheckedEntrySet.CheckedEntry<>(first, valueType)
4293                 : null;
4294         }
4295 
4296         public Entry<K, V> lastEntry() {
4297             Entry<K,V> last = nm.lastEntry();
4298             return (null != last)
4299                 ? new CheckedMap.CheckedEntrySet.CheckedEntry<>(last, valueType)
4300                 : null;
4301         }
4302 
4303         public Entry<K, V> pollFirstEntry() {
4304             Entry<K,V> entry = nm.pollFirstEntry();
4305             return (null == entry)
4306                 ? null
4307                 : new CheckedMap.CheckedEntrySet.CheckedEntry<>(entry, valueType);
4308         }
4309 
4310         public Entry<K, V> pollLastEntry() {
4311             Entry<K,V> entry = nm.pollLastEntry();
4312             return (null == entry)
4313                 ? null
4314                 : new CheckedMap.CheckedEntrySet.CheckedEntry<>(entry, valueType);
4315         }
4316 
4317         public NavigableMap<K, V> descendingMap() {
4318             return checkedNavigableMap(nm.descendingMap(), keyType, valueType);
4319         }
4320 
4321         public NavigableSet<K> keySet() {
4322             return navigableKeySet();
4323         }
4324 
4325         public NavigableSet<K> navigableKeySet() {
4326             return checkedNavigableSet(nm.navigableKeySet(), keyType);
4327         }
4328 
4329         public NavigableSet<K> descendingKeySet() {
4330             return checkedNavigableSet(nm.descendingKeySet(), keyType);
4331         }
4332 
4333         @Override
4334         public NavigableMap<K,V> subMap(K fromKey, K toKey) {
4335             return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false),
4336                                     keyType, valueType);
4337         }
4338 
4339         @Override
4340         public NavigableMap<K,V> headMap(K toKey) {
4341             return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType);
4342         }
4343 
4344         @Override
4345         public NavigableMap<K,V> tailMap(K fromKey) {
4346             return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType);
4347         }
4348 
4349         public NavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
4350             return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType);
4351         }
4352 
4353         public NavigableMap<K, V> headMap(K toKey, boolean inclusive) {
4354             return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType);
4355         }
4356 
4357         public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) {
4358             return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType);
4359         }
4360     }
4361 
4362     // Empty collections
4363 
4364     /**
4365      * Returns an iterator that has no elements.  More precisely,
4366      *
4367      * <ul>
4368      * <li>{@link Iterator#hasNext hasNext} always returns {@code
4369      * false}.</li>
4370      * <li>{@link Iterator#next next} always throws {@link
4371      * NoSuchElementException}.</li>
4372      * <li>{@link Iterator#remove remove} always throws {@link
4373      * IllegalStateException}.</li>
4374      * </ul>
4375      *
4376      * <p>Implementations of this method are permitted, but not
4377      * required, to return the same object from multiple invocations.
4378      *
4379      * @param <T> type of elements, if there were any, in the iterator
4380      * @return an empty iterator
4381      * @since 1.7
4382      */
4383     @SuppressWarnings("unchecked")
4384     public static <T> Iterator<T> emptyIterator() {
4385         return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;
4386     }
4387 
4388     private static class EmptyIterator<E> implements Iterator<E> {
4389         static final EmptyIterator<Object> EMPTY_ITERATOR
4390             = new EmptyIterator<>();
4391 
4392         public boolean hasNext() { return false; }
4393         public E next() { throw new NoSuchElementException(); }
4394         public void remove() { throw new IllegalStateException(); }
4395         @Override
4396         public void forEachRemaining(Consumer<? super E> action) {
4397             Objects.requireNonNull(action);
4398         }
4399     }
4400 
4401     /**
4402      * Returns a list iterator that has no elements.  More precisely,
4403      *
4404      * <ul>
4405      * <li>{@link Iterator#hasNext hasNext} and {@link
4406      * ListIterator#hasPrevious hasPrevious} always return {@code
4407      * false}.</li>
4408      * <li>{@link Iterator#next next} and {@link ListIterator#previous
4409      * previous} always throw {@link NoSuchElementException}.</li>
4410      * <li>{@link Iterator#remove remove} and {@link ListIterator#set
4411      * set} always throw {@link IllegalStateException}.</li>
4412      * <li>{@link ListIterator#add add} always throws {@link
4413      * UnsupportedOperationException}.</li>
4414      * <li>{@link ListIterator#nextIndex nextIndex} always returns
4415      * {@code 0}.</li>
4416      * <li>{@link ListIterator#previousIndex previousIndex} always
4417      * returns {@code -1}.</li>
4418      * </ul>
4419      *
4420      * <p>Implementations of this method are permitted, but not
4421      * required, to return the same object from multiple invocations.
4422      *
4423      * @param <T> type of elements, if there were any, in the iterator
4424      * @return an empty list iterator
4425      * @since 1.7
4426      */
4427     @SuppressWarnings("unchecked")
4428     public static <T> ListIterator<T> emptyListIterator() {
4429         return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR;
4430     }
4431 
4432     private static class EmptyListIterator<E>
4433         extends EmptyIterator<E>
4434         implements ListIterator<E>
4435     {
4436         static final EmptyListIterator<Object> EMPTY_ITERATOR
4437             = new EmptyListIterator<>();
4438 
4439         public boolean hasPrevious() { return false; }
4440         public E previous() { throw new NoSuchElementException(); }
4441         public int nextIndex()     { return 0; }
4442         public int previousIndex() { return -1; }
4443         public void set(E e) { throw new IllegalStateException(); }
4444         public void add(E e) { throw new UnsupportedOperationException(); }
4445     }
4446 
4447     /**
4448      * Returns an enumeration that has no elements.  More precisely,
4449      *
4450      * <ul>
4451      * <li>{@link Enumeration#hasMoreElements hasMoreElements} always
4452      * returns {@code false}.</li>
4453      * <li> {@link Enumeration#nextElement nextElement} always throws
4454      * {@link NoSuchElementException}.</li>
4455      * </ul>
4456      *
4457      * <p>Implementations of this method are permitted, but not
4458      * required, to return the same object from multiple invocations.
4459      *
4460      * @param  <T> the class of the objects in the enumeration
4461      * @return an empty enumeration
4462      * @since 1.7
4463      */
4464     @SuppressWarnings("unchecked")
4465     public static <T> Enumeration<T> emptyEnumeration() {
4466         return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
4467     }
4468 
4469     private static class EmptyEnumeration<E> implements Enumeration<E> {
4470         static final EmptyEnumeration<Object> EMPTY_ENUMERATION
4471             = new EmptyEnumeration<>();
4472 
4473         public boolean hasMoreElements() { return false; }
4474         public E nextElement() { throw new NoSuchElementException(); }
4475         public Iterator<E> asIterator() { return emptyIterator(); }
4476     }
4477 
4478     /**
4479      * The empty set (immutable).  This set is serializable.
4480      *
4481      * @see #emptySet()
4482      */
4483     @SuppressWarnings("rawtypes")
4484     public static final Set EMPTY_SET = new EmptySet<>();
4485 
4486     /**
4487      * Returns an empty set (immutable).  This set is serializable.
4488      * Unlike the like-named field, this method is parameterized.
4489      *
4490      * <p>This example illustrates the type-safe way to obtain an empty set:
4491      * <pre>
4492      *     Set&lt;String&gt; s = Collections.emptySet();
4493      * </pre>
4494      * @implNote Implementations of this method need not create a separate
4495      * {@code Set} object for each call.  Using this method is likely to have
4496      * comparable cost to using the like-named field.  (Unlike this method, the
4497      * field does not provide type safety.)
4498      *
4499      * @param  <T> the class of the objects in the set
4500      * @return the empty set
4501      *
4502      * @see #EMPTY_SET
4503      * @since 1.5
4504      */
4505     @SuppressWarnings("unchecked")
4506     public static final <T> Set<T> emptySet() {
4507         return (Set<T>) EMPTY_SET;
4508     }
4509 
4510     /**
4511      * @serial include
4512      */
4513     private static class EmptySet<E>
4514         extends AbstractSet<E>
4515         implements Serializable
4516     {
4517         @java.io.Serial
4518         private static final long serialVersionUID = 1582296315990362920L;
4519 
4520         public Iterator<E> iterator() { return emptyIterator(); }
4521 
4522         public int size() {return 0;}
4523         public boolean isEmpty() {return true;}
4524         public void clear() {}
4525 
4526         public boolean contains(Object obj) {return false;}
4527         public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
4528 
4529         public Object[] toArray() { return new Object[0]; }
4530 
4531         public <T> T[] toArray(T[] a) {
4532             if (a.length > 0)
4533                 a[0] = null;
4534             return a;
4535         }
4536 
4537         // Override default methods in Collection
4538         @Override
4539         public void forEach(Consumer<? super E> action) {
4540             Objects.requireNonNull(action);
4541         }
4542         @Override
4543         public boolean removeIf(Predicate<? super E> filter) {
4544             Objects.requireNonNull(filter);
4545             return false;
4546         }
4547         @Override
4548         public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4549 
4550         // Preserves singleton property
4551         @java.io.Serial
4552         private Object readResolve() {
4553             return EMPTY_SET;
4554         }
4555 
4556         @Override
4557         public int hashCode() {
4558             return 0;
4559         }
4560     }
4561 
4562     /**
4563      * Returns an empty sorted set (immutable).  This set is serializable.
4564      *
4565      * <p>This example illustrates the type-safe way to obtain an empty
4566      * sorted set:
4567      * <pre> {@code
4568      *     SortedSet<String> s = Collections.emptySortedSet();
4569      * }</pre>
4570      *
4571      * @implNote Implementations of this method need not create a separate
4572      * {@code SortedSet} object for each call.
4573      *
4574      * @param <E> type of elements, if there were any, in the set
4575      * @return the empty sorted set
4576      * @since 1.8
4577      */
4578     @SuppressWarnings("unchecked")
4579     public static <E> SortedSet<E> emptySortedSet() {
4580         return (SortedSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;
4581     }
4582 
4583     /**
4584      * Returns an empty navigable set (immutable).  This set is serializable.
4585      *
4586      * <p>This example illustrates the type-safe way to obtain an empty
4587      * navigable set:
4588      * <pre> {@code
4589      *     NavigableSet<String> s = Collections.emptyNavigableSet();
4590      * }</pre>
4591      *
4592      * @implNote Implementations of this method need not
4593      * create a separate {@code NavigableSet} object for each call.
4594      *
4595      * @param <E> type of elements, if there were any, in the set
4596      * @return the empty navigable set
4597      * @since 1.8
4598      */
4599     @SuppressWarnings("unchecked")
4600     public static <E> NavigableSet<E> emptyNavigableSet() {
4601         return (NavigableSet<E>) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET;
4602     }
4603 
4604     /**
4605      * The empty list (immutable).  This list is serializable.
4606      *
4607      * @see #emptyList()
4608      */
4609     @SuppressWarnings("rawtypes")
4610     public static final List EMPTY_LIST = new EmptyList<>();
4611 
4612     /**
4613      * Returns an empty list (immutable).  This list is serializable.
4614      *
4615      * <p>This example illustrates the type-safe way to obtain an empty list:
4616      * <pre>
4617      *     List&lt;String&gt; s = Collections.emptyList();
4618      * </pre>
4619      *
4620      * @implNote
4621      * Implementations of this method need not create a separate {@code List}
4622      * object for each call.   Using this method is likely to have comparable
4623      * cost to using the like-named field.  (Unlike this method, the field does
4624      * not provide type safety.)
4625      *
4626      * @param <T> type of elements, if there were any, in the list
4627      * @return an empty immutable list
4628      *
4629      * @see #EMPTY_LIST
4630      * @since 1.5
4631      */
4632     @SuppressWarnings("unchecked")
4633     public static final <T> List<T> emptyList() {
4634         return (List<T>) EMPTY_LIST;
4635     }
4636 
4637     /**
4638      * @serial include
4639      */
4640     private static class EmptyList<E>
4641         extends AbstractList<E>
4642         implements RandomAccess, Serializable {
4643         @java.io.Serial
4644         private static final long serialVersionUID = 8842843931221139166L;
4645 
4646         public Iterator<E> iterator() {
4647             return emptyIterator();
4648         }
4649         public ListIterator<E> listIterator() {
4650             return emptyListIterator();
4651         }
4652 
4653         public int size() {return 0;}
4654         public boolean isEmpty() {return true;}
4655         public void clear() {}
4656 
4657         public boolean contains(Object obj) {return false;}
4658         public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
4659 
4660         public Object[] toArray() { return new Object[0]; }
4661 
4662         public <T> T[] toArray(T[] a) {
4663             if (a.length > 0)
4664                 a[0] = null;
4665             return a;
4666         }
4667 
4668         public E get(int index) {
4669             throw new IndexOutOfBoundsException("Index: "+index);
4670         }
4671 
4672         public boolean equals(Object o) {
4673             return (o instanceof List) && ((List<?>)o).isEmpty();
4674         }
4675 
4676         public int hashCode() { return 1; }
4677 
4678         @Override
4679         public boolean removeIf(Predicate<? super E> filter) {
4680             Objects.requireNonNull(filter);
4681             return false;
4682         }
4683         @Override
4684         public void replaceAll(UnaryOperator<E> operator) {
4685             Objects.requireNonNull(operator);
4686         }
4687         @Override
4688         public void sort(Comparator<? super E> c) {
4689         }
4690 
4691         // Override default methods in Collection
4692         @Override
4693         public void forEach(Consumer<? super E> action) {
4694             Objects.requireNonNull(action);
4695         }
4696 
4697         @Override
4698         public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
4699 
4700         // Preserves singleton property
4701         @java.io.Serial
4702         private Object readResolve() {
4703             return EMPTY_LIST;
4704         }
4705     }
4706 
4707     /**
4708      * The empty map (immutable).  This map is serializable.
4709      *
4710      * @see #emptyMap()
4711      * @since 1.3
4712      */
4713     @SuppressWarnings("rawtypes")
4714     public static final Map EMPTY_MAP = new EmptyMap<>();
4715 
4716     /**
4717      * Returns an empty map (immutable).  This map is serializable.
4718      *
4719      * <p>This example illustrates the type-safe way to obtain an empty map:
4720      * <pre>
4721      *     Map&lt;String, Date&gt; s = Collections.emptyMap();
4722      * </pre>
4723      * @implNote Implementations of this method need not create a separate
4724      * {@code Map} object for each call.  Using this method is likely to have
4725      * comparable cost to using the like-named field.  (Unlike this method, the
4726      * field does not provide type safety.)
4727      *
4728      * @param <K> the class of the map keys
4729      * @param <V> the class of the map values
4730      * @return an empty map
4731      * @see #EMPTY_MAP
4732      * @since 1.5
4733      */
4734     @SuppressWarnings("unchecked")
4735     public static final <K,V> Map<K,V> emptyMap() {
4736         return (Map<K,V>) EMPTY_MAP;
4737     }
4738 
4739     /**
4740      * Returns an empty sorted map (immutable).  This map is serializable.
4741      *
4742      * <p>This example illustrates the type-safe way to obtain an empty map:
4743      * <pre> {@code
4744      *     SortedMap<String, Date> s = Collections.emptySortedMap();
4745      * }</pre>
4746      *
4747      * @implNote Implementations of this method need not create a separate
4748      * {@code SortedMap} object for each call.
4749      *
4750      * @param <K> the class of the map keys
4751      * @param <V> the class of the map values
4752      * @return an empty sorted map
4753      * @since 1.8
4754      */
4755     @SuppressWarnings("unchecked")
4756     public static final <K,V> SortedMap<K,V> emptySortedMap() {
4757         return (SortedMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;
4758     }
4759 
4760     /**
4761      * Returns an empty navigable map (immutable).  This map is serializable.
4762      *
4763      * <p>This example illustrates the type-safe way to obtain an empty map:
4764      * <pre> {@code
4765      *     NavigableMap<String, Date> s = Collections.emptyNavigableMap();
4766      * }</pre>
4767      *
4768      * @implNote Implementations of this method need not create a separate
4769      * {@code NavigableMap} object for each call.
4770      *
4771      * @param <K> the class of the map keys
4772      * @param <V> the class of the map values
4773      * @return an empty navigable map
4774      * @since 1.8
4775      */
4776     @SuppressWarnings("unchecked")
4777     public static final <K,V> NavigableMap<K,V> emptyNavigableMap() {
4778         return (NavigableMap<K,V>) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP;
4779     }
4780 
4781     /**
4782      * @serial include
4783      */
4784     private static class EmptyMap<K,V>
4785         extends AbstractMap<K,V>
4786         implements Serializable
4787     {
4788         @java.io.Serial
4789         private static final long serialVersionUID = 6428348081105594320L;
4790 
4791         public int size()                          {return 0;}
4792         public boolean isEmpty()                   {return true;}
4793         public void clear()                        {}
4794         public boolean containsKey(Object key)     {return false;}
4795         public boolean containsValue(Object value) {return false;}
4796         public V get(Object key)                   {return null;}
4797         public Set<K> keySet()                     {return emptySet();}
4798         public Collection<V> values()              {return emptySet();}
4799         public Set<Map.Entry<K,V>> entrySet()      {return emptySet();}
4800 
4801         public boolean equals(Object o) {
4802             return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
4803         }
4804 
4805         public int hashCode()                      {return 0;}
4806 
4807         // Override default methods in Map
4808         @Override
4809         @SuppressWarnings("unchecked")
4810         public V getOrDefault(Object k, V defaultValue) {
4811             return defaultValue;
4812         }
4813 
4814         @Override
4815         public void forEach(BiConsumer<? super K, ? super V> action) {
4816             Objects.requireNonNull(action);
4817         }
4818 
4819         @Override
4820         public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
4821             Objects.requireNonNull(function);
4822         }
4823 
4824         @Override
4825         public V putIfAbsent(K key, V value) {
4826             throw new UnsupportedOperationException();
4827         }
4828 
4829         @Override
4830         public boolean remove(Object key, Object value) {
4831             throw new UnsupportedOperationException();
4832         }
4833 
4834         @Override
4835         public boolean replace(K key, V oldValue, V newValue) {
4836             throw new UnsupportedOperationException();
4837         }
4838 
4839         @Override
4840         public V replace(K key, V value) {
4841             throw new UnsupportedOperationException();
4842         }
4843 
4844         @Override
4845         public V computeIfAbsent(K key,
4846                 Function<? super K, ? extends V> mappingFunction) {
4847             throw new UnsupportedOperationException();
4848         }
4849 
4850         @Override
4851         public V computeIfPresent(K key,
4852                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4853             throw new UnsupportedOperationException();
4854         }
4855 
4856         @Override
4857         public V compute(K key,
4858                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
4859             throw new UnsupportedOperationException();
4860         }
4861 
4862         @Override
4863         public V merge(K key, V value,
4864                 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
4865             throw new UnsupportedOperationException();
4866         }
4867 
4868         // Preserves singleton property
4869         @java.io.Serial
4870         private Object readResolve() {
4871             return EMPTY_MAP;
4872         }
4873     }
4874 
4875     // Singleton collections
4876 
4877     /**
4878      * Returns an immutable set containing only the specified object.
4879      * The returned set is serializable.
4880      *
4881      * @param  <T> the class of the objects in the set
4882      * @param o the sole object to be stored in the returned set.
4883      * @return an immutable set containing only the specified object.
4884      */
4885     public static <T> Set<T> singleton(T o) {
4886         return new SingletonSet<>(o);
4887     }
4888 
4889     static <E> Iterator<E> singletonIterator(final E e) {
4890         return new Iterator<E>() {
4891             private boolean hasNext = true;
4892             public boolean hasNext() {
4893                 return hasNext;
4894             }
4895             public E next() {
4896                 if (hasNext) {
4897                     hasNext = false;
4898                     return e;
4899                 }
4900                 throw new NoSuchElementException();
4901             }
4902             public void remove() {
4903                 throw new UnsupportedOperationException();
4904             }
4905             @Override
4906             public void forEachRemaining(Consumer<? super E> action) {
4907                 Objects.requireNonNull(action);
4908                 if (hasNext) {
4909                     hasNext = false;
4910                     action.accept(e);
4911                 }
4912             }
4913         };
4914     }
4915 
4916     /**
4917      * Creates a {@code Spliterator} with only the specified element
4918      *
4919      * @param <T> Type of elements
4920      * @return A singleton {@code Spliterator}
4921      */
4922     static <T> Spliterator<T> singletonSpliterator(final T element) {
4923         return new Spliterator<T>() {
4924             long est = 1;
4925 
4926             @Override
4927             public Spliterator<T> trySplit() {
4928                 return null;
4929             }
4930 
4931             @Override
4932             public boolean tryAdvance(Consumer<? super T> consumer) {
4933                 Objects.requireNonNull(consumer);
4934                 if (est > 0) {
4935                     est--;
4936                     consumer.accept(element);
4937                     return true;
4938                 }
4939                 return false;
4940             }
4941 
4942             @Override
4943             public void forEachRemaining(Consumer<? super T> consumer) {
4944                 tryAdvance(consumer);
4945             }
4946 
4947             @Override
4948             public long estimateSize() {
4949                 return est;
4950             }
4951 
4952             @Override
4953             public int characteristics() {
4954                 int value = (element != null) ? Spliterator.NONNULL : 0;
4955 
4956                 return value | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE |
4957                        Spliterator.DISTINCT | Spliterator.ORDERED;
4958             }
4959         };
4960     }
4961 
4962     /**
4963      * @serial include
4964      */
4965     private static class SingletonSet<E>
4966         extends AbstractSet<E>
4967         implements Serializable
4968     {
4969         @java.io.Serial
4970         private static final long serialVersionUID = 3193687207550431679L;
4971 
4972         @SuppressWarnings("serial") // Conditionally serializable
4973         private final E element;
4974 
4975         SingletonSet(E e) {element = e;}
4976 
4977         public Iterator<E> iterator() {
4978             return singletonIterator(element);
4979         }
4980 
4981         public int size() {return 1;}
4982 
4983         public boolean contains(Object o) {return eq(o, element);}
4984 
4985         // Override default methods for Collection
4986         @Override
4987         public void forEach(Consumer<? super E> action) {
4988             action.accept(element);
4989         }
4990         @Override
4991         public Spliterator<E> spliterator() {
4992             return singletonSpliterator(element);
4993         }
4994         @Override
4995         public boolean removeIf(Predicate<? super E> filter) {
4996             throw new UnsupportedOperationException();
4997         }
4998         @Override
4999         public int hashCode() {
5000             return Objects.hashCode(element);
5001         }
5002     }
5003 
5004     /**
5005      * Returns an immutable list containing only the specified object.
5006      * The returned list is serializable.
5007      *
5008      * @param  <T> the class of the objects in the list
5009      * @param o the sole object to be stored in the returned list.
5010      * @return an immutable list containing only the specified object.
5011      * @since 1.3
5012      */
5013     public static <T> List<T> singletonList(T o) {
5014         return new SingletonList<>(o);
5015     }
5016 
5017     /**
5018      * @serial include
5019      */
5020     private static class SingletonList<E>
5021         extends AbstractList<E>
5022         implements RandomAccess, Serializable {
5023 
5024         @java.io.Serial
5025         private static final long serialVersionUID = 3093736618740652951L;
5026 
5027         @SuppressWarnings("serial") // Conditionally serializable
5028         private final E element;
5029 
5030         SingletonList(E obj)                {element = obj;}
5031 
5032         public Iterator<E> iterator() {
5033             return singletonIterator(element);
5034         }
5035 
5036         public int size()                   {return 1;}
5037 
5038         public boolean contains(Object obj) {return eq(obj, element);}
5039 
5040         public E get(int index) {
5041             if (index != 0)
5042               throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
5043             return element;
5044         }
5045 
5046         // Override default methods for Collection
5047         @Override
5048         public void forEach(Consumer<? super E> action) {
5049             action.accept(element);
5050         }
5051         @Override
5052         public boolean removeIf(Predicate<? super E> filter) {
5053             throw new UnsupportedOperationException();
5054         }
5055         @Override
5056         public void replaceAll(UnaryOperator<E> operator) {
5057             throw new UnsupportedOperationException();
5058         }
5059         @Override
5060         public void sort(Comparator<? super E> c) {
5061         }
5062         @Override
5063         public Spliterator<E> spliterator() {
5064             return singletonSpliterator(element);
5065         }
5066         @Override
5067         public int hashCode() {
5068             return 31 + Objects.hashCode(element);
5069         }
5070     }
5071 
5072     /**
5073      * Returns an immutable map, mapping only the specified key to the
5074      * specified value.  The returned map is serializable.
5075      *
5076      * @param <K> the class of the map keys
5077      * @param <V> the class of the map values
5078      * @param key the sole key to be stored in the returned map.
5079      * @param value the value to which the returned map maps {@code key}.
5080      * @return an immutable map containing only the specified key-value
5081      *         mapping.
5082      * @since 1.3
5083      */
5084     public static <K,V> Map<K,V> singletonMap(K key, V value) {
5085         return new SingletonMap<>(key, value);
5086     }
5087 
5088     /**
5089      * @serial include
5090      */
5091     private static class SingletonMap<K,V>
5092           extends AbstractMap<K,V>
5093           implements Serializable {
5094         @java.io.Serial
5095         private static final long serialVersionUID = -6979724477215052911L;
5096 
5097         @SuppressWarnings("serial") // Conditionally serializable
5098         private final K k;
5099         @SuppressWarnings("serial") // Conditionally serializable
5100         private final V v;
5101 
5102         SingletonMap(K key, V value) {
5103             k = key;
5104             v = value;
5105         }
5106 
5107         public int size()                                           {return 1;}
5108         public boolean isEmpty()                                {return false;}
5109         public boolean containsKey(Object key)             {return eq(key, k);}
5110         public boolean containsValue(Object value)       {return eq(value, v);}
5111         public V get(Object key)              {return (eq(key, k) ? v : null);}
5112 
5113         private transient Set<K> keySet;
5114         private transient Set<Map.Entry<K,V>> entrySet;
5115         private transient Collection<V> values;
5116 
5117         public Set<K> keySet() {
5118             if (keySet==null)
5119                 keySet = singleton(k);
5120             return keySet;
5121         }
5122 
5123         public Set<Map.Entry<K,V>> entrySet() {
5124             if (entrySet==null)
5125                 entrySet = Collections.<Map.Entry<K,V>>singleton(
5126                     new SimpleImmutableEntry<>(k, v));
5127             return entrySet;
5128         }
5129 
5130         public Collection<V> values() {
5131             if (values==null)
5132                 values = singleton(v);
5133             return values;
5134         }
5135 
5136         // Override default methods in Map
5137         @Override
5138         public V getOrDefault(Object key, V defaultValue) {
5139             return eq(key, k) ? v : defaultValue;
5140         }
5141 
5142         @Override
5143         public void forEach(BiConsumer<? super K, ? super V> action) {
5144             action.accept(k, v);
5145         }
5146 
5147         @Override
5148         public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
5149             throw new UnsupportedOperationException();
5150         }
5151 
5152         @Override
5153         public V putIfAbsent(K key, V value) {
5154             throw new UnsupportedOperationException();
5155         }
5156 
5157         @Override
5158         public boolean remove(Object key, Object value) {
5159             throw new UnsupportedOperationException();
5160         }
5161 
5162         @Override
5163         public boolean replace(K key, V oldValue, V newValue) {
5164             throw new UnsupportedOperationException();
5165         }
5166 
5167         @Override
5168         public V replace(K key, V value) {
5169             throw new UnsupportedOperationException();
5170         }
5171 
5172         @Override
5173         public V computeIfAbsent(K key,
5174                 Function<? super K, ? extends V> mappingFunction) {
5175             throw new UnsupportedOperationException();
5176         }
5177 
5178         @Override
5179         public V computeIfPresent(K key,
5180                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
5181             throw new UnsupportedOperationException();
5182         }
5183 
5184         @Override
5185         public V compute(K key,
5186                 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
5187             throw new UnsupportedOperationException();
5188         }
5189 
5190         @Override
5191         public V merge(K key, V value,
5192                 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
5193             throw new UnsupportedOperationException();
5194         }
5195 
5196         @Override
5197         public int hashCode() {
5198             return Objects.hashCode(k) ^ Objects.hashCode(v);
5199         }
5200     }
5201 
5202     // Miscellaneous
5203 
5204     /**
5205      * Returns an immutable list consisting of {@code n} copies of the
5206      * specified object.  The newly allocated data object is tiny (it contains
5207      * a single reference to the data object).  This method is useful in
5208      * combination with the {@code List.addAll} method to grow lists.
5209      * The returned list is serializable.
5210      *
5211      * @param  <T> the class of the object to copy and of the objects
5212      *         in the returned list.
5213      * @param  n the number of elements in the returned list.
5214      * @param  o the element to appear repeatedly in the returned list.
5215      * @return an immutable list consisting of {@code n} copies of the
5216      *         specified object.
5217      * @throws IllegalArgumentException if {@code n < 0}
5218      * @see    List#addAll(Collection)
5219      * @see    List#addAll(int, Collection)
5220      */
5221     public static <T> List<T> nCopies(int n, T o) {
5222         if (n < 0)
5223             throw new IllegalArgumentException("List length = " + n);
5224         return new CopiesList<>(n, o);
5225     }
5226 
5227     /**
5228      * @serial include
5229      */
5230     private static class CopiesList<E>
5231         extends AbstractList<E>
5232         implements RandomAccess, Serializable
5233     {
5234         @java.io.Serial
5235         private static final long serialVersionUID = 2739099268398711800L;
5236 
5237         final int n;
5238         @SuppressWarnings("serial") // Conditionally serializable
5239         final E element;
5240 
5241         CopiesList(int n, E e) {
5242             assert n >= 0;
5243             this.n = n;
5244             element = e;
5245         }
5246 
5247         public int size() {
5248             return n;
5249         }
5250 
5251         public boolean contains(Object obj) {
5252             return n != 0 && eq(obj, element);
5253         }
5254 
5255         public int indexOf(Object o) {
5256             return contains(o) ? 0 : -1;
5257         }
5258 
5259         public int lastIndexOf(Object o) {
5260             return contains(o) ? n - 1 : -1;
5261         }
5262 
5263         public E get(int index) {
5264             if (index < 0 || index >= n)
5265                 throw new IndexOutOfBoundsException("Index: "+index+
5266                                                     ", Size: "+n);
5267             return element;
5268         }
5269 
5270         public Object[] toArray() {
5271             final Object[] a = new Object[n];
5272             if (element != null)
5273                 Arrays.fill(a, 0, n, element);
5274             return a;
5275         }
5276 
5277         @SuppressWarnings("unchecked")
5278         public <T> T[] toArray(T[] a) {
5279             final int n = this.n;
5280             if (a.length < n) {
5281                 a = (T[])java.lang.reflect.Array
5282                     .newInstance(a.getClass().getComponentType(), n);
5283                 if (element != null)
5284                     Arrays.fill(a, 0, n, element);
5285             } else {
5286                 Arrays.fill(a, 0, n, element);
5287                 if (a.length > n)
5288                     a[n] = null;
5289             }
5290             return a;
5291         }
5292 
5293         public List<E> subList(int fromIndex, int toIndex) {
5294             if (fromIndex < 0)
5295                 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
5296             if (toIndex > n)
5297                 throw new IndexOutOfBoundsException("toIndex = " + toIndex);
5298             if (fromIndex > toIndex)
5299                 throw new IllegalArgumentException("fromIndex(" + fromIndex +
5300                                                    ") > toIndex(" + toIndex + ")");
5301             return new CopiesList<>(toIndex - fromIndex, element);
5302         }
5303 
5304         @Override
5305         public int hashCode() {
5306             if (n == 0) return 1;
5307             // hashCode of n repeating elements is 31^n + elementHash * Sum(31^k, k = 0..n-1)
5308             // this implementation completes in O(log(n)) steps taking advantage of
5309             // 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)
5310             int pow = 31;
5311             int sum = 1;
5312             for (int i = Integer.numberOfLeadingZeros(n) + 1; i < Integer.SIZE; i++) {
5313                 sum *= pow + 1;
5314                 pow *= pow;
5315                 if ((n << i) < 0) {
5316                     pow *= 31;
5317                     sum = sum * 31 + 1;
5318                 }
5319             }
5320             return pow + sum * (element == null ? 0 : element.hashCode());
5321         }
5322 
5323         @Override
5324         public boolean equals(Object o) {
5325             if (o == this)
5326                 return true;
5327             // Android-changed: (b/247094511) instanceof pattern variable is not yet supported.
5328             // if (o instanceof CopiesList<?> other) {
5329             if (o instanceof CopiesList<?>) {
5330                 CopiesList<?> other = (CopiesList<?>) o;
5331                 return n == other.n && (n == 0 || eq(element, other.element));
5332             }
5333             if (!(o instanceof List))
5334                 return false;
5335 
5336             int remaining = n;
5337             E e = element;
5338             Iterator<?> itr = ((List<?>) o).iterator();
5339             if (e == null) {
5340                 while (itr.hasNext() && remaining-- > 0) {
5341                     if (itr.next() != null)
5342                         return false;
5343                 }
5344             } else {
5345                 while (itr.hasNext() && remaining-- > 0) {
5346                     if (!e.equals(itr.next()))
5347                         return false;
5348                 }
5349             }
5350             return remaining == 0 && !itr.hasNext();
5351         }
5352 
5353         // Override default methods in Collection
5354         @Override
5355         public Stream<E> stream() {
5356             return IntStream.range(0, n).mapToObj(i -> element);
5357         }
5358 
5359         @Override
5360         public Stream<E> parallelStream() {
5361             return IntStream.range(0, n).parallel().mapToObj(i -> element);
5362         }
5363 
5364         @Override
5365         public Spliterator<E> spliterator() {
5366             return stream().spliterator();
5367         }
5368 
5369         @java.io.Serial
5370         private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
5371             ois.defaultReadObject();
5372             SharedSecrets.getJavaObjectInputStreamAccess().checkArray(ois, Object[].class, n);
5373         }
5374     }
5375 
5376     /**
5377      * Returns a comparator that imposes the reverse of the <em>natural
5378      * ordering</em> on a collection of objects that implement the
5379      * {@code Comparable} interface.  (The natural ordering is the ordering
5380      * imposed by the objects' own {@code compareTo} method.)  This enables a
5381      * simple idiom for sorting (or maintaining) collections (or arrays) of
5382      * objects that implement the {@code Comparable} interface in
5383      * reverse-natural-order.  For example, suppose {@code a} is an array of
5384      * strings. Then: <pre>
5385      *          Arrays.sort(a, Collections.reverseOrder());
5386      * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
5387      *
5388      * The returned comparator is serializable.
5389      *
5390      * @param  <T> the class of the objects compared by the comparator
5391      * @return A comparator that imposes the reverse of the <i>natural
5392      *         ordering</i> on a collection of objects that implement
5393      *         the {@code Comparable} interface.
5394      * @see Comparable
5395      */
5396     @SuppressWarnings("unchecked")
5397     public static <T> Comparator<T> reverseOrder() {
5398         return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5399     }
5400 
5401     /**
5402      * @serial include
5403      */
5404     private static class ReverseComparator
5405         implements Comparator<Comparable<Object>>, Serializable {
5406 
5407         @java.io.Serial
5408         private static final long serialVersionUID = 7207038068494060240L;
5409 
5410         static final ReverseComparator REVERSE_ORDER
5411             = new ReverseComparator();
5412 
5413         public int compare(Comparable<Object> c1, Comparable<Object> c2) {
5414             return c2.compareTo(c1);
5415         }
5416 
5417         @java.io.Serial
5418         private Object readResolve() { return Collections.reverseOrder(); }
5419 
5420         @Override
5421         public Comparator<Comparable<Object>> reversed() {
5422             return Comparator.naturalOrder();
5423         }
5424     }
5425 
5426     /**
5427      * Returns a comparator that imposes the reverse ordering of the specified
5428      * comparator.  If the specified comparator is {@code null}, this method is
5429      * equivalent to {@link #reverseOrder()} (in other words, it returns a
5430      * comparator that imposes the reverse of the <em>natural ordering</em> on
5431      * a collection of objects that implement the Comparable interface).
5432      *
5433      * <p>The returned comparator is serializable (assuming the specified
5434      * comparator is also serializable or {@code null}).
5435      *
5436      * @param <T> the class of the objects compared by the comparator
5437      * @param cmp a comparator who's ordering is to be reversed by the returned
5438      * comparator or {@code null}
5439      * @return A comparator that imposes the reverse ordering of the
5440      *         specified comparator.
5441      * @since 1.5
5442      */
5443     @SuppressWarnings("unchecked")
5444     public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
5445         if (cmp == null) {
5446             return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5447         } else if (cmp == ReverseComparator.REVERSE_ORDER) {
5448             return (Comparator<T>) Comparators.NaturalOrderComparator.INSTANCE;
5449         } else if (cmp == Comparators.NaturalOrderComparator.INSTANCE) {
5450             return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
5451         } else if (cmp instanceof ReverseComparator2) {
5452             return ((ReverseComparator2<T>) cmp).cmp;
5453         } else {
5454             return new ReverseComparator2<>(cmp);
5455         }
5456     }
5457 
5458     /**
5459      * @serial include
5460      */
5461     private static class ReverseComparator2<T> implements Comparator<T>,
5462         Serializable
5463     {
5464         @java.io.Serial
5465         private static final long serialVersionUID = 4374092139857L;
5466 
5467         /**
5468          * The comparator specified in the static factory.  This will never
5469          * be null, as the static factory returns a ReverseComparator
5470          * instance if its argument is null.
5471          *
5472          * @serial
5473          */
5474         @SuppressWarnings("serial") // Conditionally serializable
5475         final Comparator<T> cmp;
5476 
5477         ReverseComparator2(Comparator<T> cmp) {
5478             assert cmp != null;
5479             this.cmp = cmp;
5480         }
5481 
5482         public int compare(T t1, T t2) {
5483             return cmp.compare(t2, t1);
5484         }
5485 
5486         public boolean equals(Object o) {
5487             return (o == this) ||
5488                 (o instanceof ReverseComparator2 &&
5489                  cmp.equals(((ReverseComparator2)o).cmp));
5490         }
5491 
5492         public int hashCode() {
5493             return cmp.hashCode() ^ Integer.MIN_VALUE;
5494         }
5495 
5496         @Override
5497         public Comparator<T> reversed() {
5498             return cmp;
5499         }
5500     }
5501 
5502     /**
5503      * Returns an enumeration over the specified collection.  This provides
5504      * interoperability with legacy APIs that require an enumeration
5505      * as input.
5506      *
5507      * <p>The iterator returned from a call to {@link Enumeration#asIterator()}
5508      * does not support removal of elements from the specified collection.  This
5509      * is necessary to avoid unintentionally increasing the capabilities of the
5510      * returned enumeration.
5511      *
5512      * @param  <T> the class of the objects in the collection
5513      * @param c the collection for which an enumeration is to be returned.
5514      * @return an enumeration over the specified collection.
5515      * @see Enumeration
5516      */
5517     public static <T> Enumeration<T> enumeration(final Collection<T> c) {
5518         return new Enumeration<T>() {
5519             private final Iterator<T> i = c.iterator();
5520 
5521             public boolean hasMoreElements() {
5522                 return i.hasNext();
5523             }
5524 
5525             public T nextElement() {
5526                 return i.next();
5527             }
5528         };
5529     }
5530 
5531     /**
5532      * Returns an array list containing the elements returned by the
5533      * specified enumeration in the order they are returned by the
5534      * enumeration.  This method provides interoperability between
5535      * legacy APIs that return enumerations and new APIs that require
5536      * collections.
5537      *
5538      * @param <T> the class of the objects returned by the enumeration
5539      * @param e enumeration providing elements for the returned
5540      *          array list
5541      * @return an array list containing the elements returned
5542      *         by the specified enumeration.
5543      * @since 1.4
5544      * @see Enumeration
5545      * @see ArrayList
5546      */
5547     public static <T> ArrayList<T> list(Enumeration<T> e) {
5548         ArrayList<T> l = new ArrayList<>();
5549         while (e.hasMoreElements())
5550             l.add(e.nextElement());
5551         return l;
5552     }
5553 
5554     /**
5555      * Returns true if the specified arguments are equal, or both null.
5556      *
5557      * NB: Do not replace with Object.equals until JDK-8015417 is resolved.
5558      */
5559     static boolean eq(Object o1, Object o2) {
5560         return o1==null ? o2==null : o1.equals(o2);
5561     }
5562 
5563     /**
5564      * Returns the number of elements in the specified collection equal to the
5565      * specified object.  More formally, returns the number of elements
5566      * {@code e} in the collection such that
5567      * {@code Objects.equals(o, e)}.
5568      *
5569      * @param c the collection in which to determine the frequency
5570      *     of {@code o}
5571      * @param o the object whose frequency is to be determined
5572      * @return the number of elements in {@code c} equal to {@code o}
5573      * @throws NullPointerException if {@code c} is null
5574      * @since 1.5
5575      */
5576     public static int frequency(Collection<?> c, Object o) {
5577         int result = 0;
5578         if (o == null) {
5579             for (Object e : c)
5580                 if (e == null)
5581                     result++;
5582         } else {
5583             for (Object e : c)
5584                 if (o.equals(e))
5585                     result++;
5586         }
5587         return result;
5588     }
5589 
5590     /**
5591      * Returns {@code true} if the two specified collections have no
5592      * elements in common.
5593      *
5594      * <p>Care must be exercised if this method is used on collections that
5595      * do not comply with the general contract for {@code Collection}.
5596      * Implementations may elect to iterate over either collection and test
5597      * for containment in the other collection (or to perform any equivalent
5598      * computation).  If either collection uses a nonstandard equality test
5599      * (as does a {@link SortedSet} whose ordering is not <em>compatible with
5600      * equals</em>, or the key set of an {@link IdentityHashMap}), both
5601      * collections must use the same nonstandard equality test, or the
5602      * result of this method is undefined.
5603      *
5604      * <p>Care must also be exercised when using collections that have
5605      * restrictions on the elements that they may contain. Collection
5606      * implementations are allowed to throw exceptions for any operation
5607      * involving elements they deem ineligible. For absolute safety the
5608      * specified collections should contain only elements which are
5609      * eligible elements for both collections.
5610      *
5611      * <p>Note that it is permissible to pass the same collection in both
5612      * parameters, in which case the method will return {@code true} if and
5613      * only if the collection is empty.
5614      *
5615      * @param c1 a collection
5616      * @param c2 a collection
5617      * @return {@code true} if the two specified collections have no
5618      * elements in common.
5619      * @throws NullPointerException if either collection is {@code null}.
5620      * @throws NullPointerException if one collection contains a {@code null}
5621      * element and {@code null} is not an eligible element for the other collection.
5622      * (<a href="Collection.html#optional-restrictions">optional</a>)
5623      * @throws ClassCastException if one collection contains an element that is
5624      * of a type which is ineligible for the other collection.
5625      * (<a href="Collection.html#optional-restrictions">optional</a>)
5626      * @since 1.5
5627      */
5628     public static boolean disjoint(Collection<?> c1, Collection<?> c2) {
5629         // The collection to be used for contains(). Preference is given to
5630         // the collection who's contains() has lower O() complexity.
5631         Collection<?> contains = c2;
5632         // The collection to be iterated. If the collections' contains() impl
5633         // are of different O() complexity, the collection with slower
5634         // contains() will be used for iteration. For collections who's
5635         // contains() are of the same complexity then best performance is
5636         // achieved by iterating the smaller collection.
5637         Collection<?> iterate = c1;
5638 
5639         // Performance optimization cases. The heuristics:
5640         //   1. Generally iterate over c1.
5641         //   2. If c1 is a Set then iterate over c2.
5642         //   3. If either collection is empty then result is always true.
5643         //   4. Iterate over the smaller Collection.
5644         if (c1 instanceof Set) {
5645             // Use c1 for contains as a Set's contains() is expected to perform
5646             // better than O(N/2)
5647             iterate = c2;
5648             contains = c1;
5649         } else if (!(c2 instanceof Set)) {
5650             // Both are mere Collections. Iterate over smaller collection.
5651             // Example: If c1 contains 3 elements and c2 contains 50 elements and
5652             // assuming contains() requires ceiling(N/2) comparisons then
5653             // checking for all c1 elements in c2 would require 75 comparisons
5654             // (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring
5655             // 100 comparisons (50 * ceiling(3/2)).
5656             int c1size = c1.size();
5657             int c2size = c2.size();
5658             if (c1size == 0 || c2size == 0) {
5659                 // At least one collection is empty. Nothing will match.
5660                 return true;
5661             }
5662 
5663             if (c1size > c2size) {
5664                 iterate = c2;
5665                 contains = c1;
5666             }
5667         }
5668 
5669         for (Object e : iterate) {
5670             if (contains.contains(e)) {
5671                // Found a common element. Collections are not disjoint.
5672                 return false;
5673             }
5674         }
5675 
5676         // No common elements were found.
5677         return true;
5678     }
5679 
5680     /**
5681      * Adds all of the specified elements to the specified collection.
5682      * Elements to be added may be specified individually or as an array.
5683      * The behaviour of this convenience method is similar to that of
5684      * {@code cc.addAll(Collections.unmodifiableList(Arrays.asList(elements)))}.
5685      *
5686      * <p>When elements are specified individually, this method provides a
5687      * convenient way to add a few elements to an existing collection:
5688      * <pre>
5689      *     Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
5690      * </pre>
5691      *
5692      * @param  <T> the class of the elements to add and of the collection
5693      * @param c the collection into which {@code elements} are to be inserted
5694      * @param elements the elements to insert into {@code c}
5695      * @return {@code true} if the collection changed as a result of the call
5696      * @throws UnsupportedOperationException if {@code c} does not support
5697      *         the {@code add} operation
5698      * @throws NullPointerException if {@code elements} contains one or more
5699      *         null values and {@code c} does not permit null elements, or
5700      *         if {@code c} or {@code elements} are {@code null}
5701      * @throws IllegalArgumentException if some property of a value in
5702      *         {@code elements} prevents it from being added to {@code c}
5703      * @see Collection#addAll(Collection)
5704      * @since 1.5
5705      */
5706     @SafeVarargs
5707     public static <T> boolean addAll(Collection<? super T> c, T... elements) {
5708         boolean result = false;
5709         for (T element : elements)
5710             result |= c.add(element);
5711         return result;
5712     }
5713 
5714     /**
5715      * Returns a set backed by the specified map.  The resulting set displays
5716      * the same ordering, concurrency, and performance characteristics as the
5717      * backing map.  In essence, this factory method provides a {@link Set}
5718      * implementation corresponding to any {@link Map} implementation.  There
5719      * is no need to use this method on a {@link Map} implementation that
5720      * already has a corresponding {@link Set} implementation (such as {@link
5721      * HashMap} or {@link TreeMap}).
5722      *
5723      * <p>Each method invocation on the set returned by this method results in
5724      * exactly one method invocation on the backing map or its {@code keySet}
5725      * view, with one exception.  The {@code addAll} method is implemented
5726      * as a sequence of {@code put} invocations on the backing map.
5727      *
5728      * <p>The specified map must be empty at the time this method is invoked,
5729      * and should not be accessed directly after this method returns.  These
5730      * conditions are ensured if the map is created empty, passed directly
5731      * to this method, and no reference to the map is retained, as illustrated
5732      * in the following code fragment:
5733      * <pre>
5734      *    Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap(
5735      *        new WeakHashMap&lt;Object, Boolean&gt;());
5736      * </pre>
5737      *
5738      * @param <E> the class of the map keys and of the objects in the
5739      *        returned set
5740      * @param map the backing map
5741      * @return the set backed by the map
5742      * @throws IllegalArgumentException if {@code map} is not empty
5743      * @since 1.6
5744      */
5745     public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
5746         return new SetFromMap<>(map);
5747     }
5748 
5749     /**
5750      * @serial include
5751      */
5752     private static class SetFromMap<E> extends AbstractSet<E>
5753         implements Set<E>, Serializable
5754     {
5755         @SuppressWarnings("serial") // Conditionally serializable
5756         private final Map<E, Boolean> m;  // The backing map
5757         private transient Set<E> s;       // Its keySet
5758 
5759         SetFromMap(Map<E, Boolean> map) {
5760             if (!map.isEmpty())
5761                 throw new IllegalArgumentException("Map is non-empty");
5762             m = map;
5763             s = map.keySet();
5764         }
5765 
5766         public void clear()               {        m.clear(); }
5767         public int size()                 { return m.size(); }
5768         public boolean isEmpty()          { return m.isEmpty(); }
5769         public boolean contains(Object o) { return m.containsKey(o); }
5770         public boolean remove(Object o)   { return m.remove(o) != null; }
5771         public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }
5772         public Iterator<E> iterator()     { return s.iterator(); }
5773         public Object[] toArray()         { return s.toArray(); }
5774         public <T> T[] toArray(T[] a)     { return s.toArray(a); }
5775         public String toString()          { return s.toString(); }
5776         public int hashCode()             { return s.hashCode(); }
5777         public boolean equals(Object o)   { return o == this || s.equals(o); }
5778         public boolean containsAll(Collection<?> c) {return s.containsAll(c);}
5779         public boolean removeAll(Collection<?> c)   {return s.removeAll(c);}
5780         public boolean retainAll(Collection<?> c)   {return s.retainAll(c);}
5781         // addAll is the only inherited implementation
5782 
5783         // Override default methods in Collection
5784         @Override
5785         public void forEach(Consumer<? super E> action) {
5786             s.forEach(action);
5787         }
5788         @Override
5789         public boolean removeIf(Predicate<? super E> filter) {
5790             return s.removeIf(filter);
5791         }
5792 
5793         @Override
5794         public Spliterator<E> spliterator() {return s.spliterator();}
5795         @Override
5796         public Stream<E> stream()           {return s.stream();}
5797         @Override
5798         public Stream<E> parallelStream()   {return s.parallelStream();}
5799 
5800         @java.io.Serial
5801         private static final long serialVersionUID = 2454657854757543876L;
5802 
5803         @java.io.Serial
5804         private void readObject(java.io.ObjectInputStream stream)
5805             throws IOException, ClassNotFoundException
5806         {
5807             stream.defaultReadObject();
5808             s = m.keySet();
5809         }
5810     }
5811 
5812     /**
5813      * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
5814      * {@link Queue}. Method {@code add} is mapped to {@code push},
5815      * {@code remove} is mapped to {@code pop} and so on. This
5816      * view can be useful when you would like to use a method
5817      * requiring a {@code Queue} but you need Lifo ordering.
5818      *
5819      * <p>Each method invocation on the queue returned by this method
5820      * results in exactly one method invocation on the backing deque, with
5821      * one exception.  The {@link Queue#addAll addAll} method is
5822      * implemented as a sequence of {@link Deque#addFirst addFirst}
5823      * invocations on the backing deque.
5824      *
5825      * @param  <T> the class of the objects in the deque
5826      * @param deque the deque
5827      * @return the queue
5828      * @since  1.6
5829      */
5830     public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
5831         return new AsLIFOQueue<>(Objects.requireNonNull(deque));
5832     }
5833 
5834     /**
5835      * @serial include
5836      */
5837     static class AsLIFOQueue<E> extends AbstractQueue<E>
5838         implements Queue<E>, Serializable {
5839         @java.io.Serial
5840         private static final long serialVersionUID = 1802017725587941708L;
5841         @SuppressWarnings("serial") // Conditionally serializable
5842         private final Deque<E> q;
5843         AsLIFOQueue(Deque<E> q)                     { this.q = q; }
5844         public boolean add(E e)                     { q.addFirst(e); return true; }
5845         public boolean offer(E e)                   { return q.offerFirst(e); }
5846         public E poll()                             { return q.pollFirst(); }
5847         public E remove()                           { return q.removeFirst(); }
5848         public E peek()                             { return q.peekFirst(); }
5849         public E element()                          { return q.getFirst(); }
5850         public void clear()                         {        q.clear(); }
5851         public int size()                           { return q.size(); }
5852         public boolean isEmpty()                    { return q.isEmpty(); }
5853         public boolean contains(Object o)           { return q.contains(o); }
5854         public boolean remove(Object o)             { return q.remove(o); }
5855         public Iterator<E> iterator()               { return q.iterator(); }
5856         public Object[] toArray()                   { return q.toArray(); }
5857         public <T> T[] toArray(T[] a)               { return q.toArray(a); }
5858         public <T> T[] toArray(IntFunction<T[]> f)  { return q.toArray(f); }
5859         public String toString()                    { return q.toString(); }
5860         public boolean containsAll(Collection<?> c) { return q.containsAll(c); }
5861         public boolean removeAll(Collection<?> c)   { return q.removeAll(c); }
5862         public boolean retainAll(Collection<?> c)   { return q.retainAll(c); }
5863         // We use inherited addAll; forwarding addAll would be wrong
5864 
5865         // Override default methods in Collection
5866         @Override
5867         public void forEach(Consumer<? super E> action) {q.forEach(action);}
5868         @Override
5869         public boolean removeIf(Predicate<? super E> filter) {
5870             return q.removeIf(filter);
5871         }
5872         @Override
5873         public Spliterator<E> spliterator() {return q.spliterator();}
5874         @Override
5875         public Stream<E> stream()           {return q.stream();}
5876         @Override
5877         public Stream<E> parallelStream()   {return q.parallelStream();}
5878     }
5879 }
5880