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