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