Collections.java revision 60796efea3a74e02aea384b8eb56103ea21b880b
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            };
1087        }
1088
1089        public boolean add(E e) {
1090            throw new UnsupportedOperationException();
1091        }
1092        public boolean remove(Object o) {
1093            throw new UnsupportedOperationException();
1094        }
1095
1096        public boolean containsAll(Collection<?> coll) {
1097            return c.containsAll(coll);
1098        }
1099        public boolean addAll(Collection<? extends E> coll) {
1100            throw new UnsupportedOperationException();
1101        }
1102        public boolean removeAll(Collection<?> coll) {
1103            throw new UnsupportedOperationException();
1104        }
1105        public boolean retainAll(Collection<?> coll) {
1106            throw new UnsupportedOperationException();
1107        }
1108        public void clear() {
1109            throw new UnsupportedOperationException();
1110        }
1111
1112        // Override default methods in Collection
1113        @Override
1114        public void forEach(Consumer<? super E> action) {
1115            c.forEach(action);
1116        }
1117    }
1118
1119    /**
1120     * Returns an unmodifiable view of the specified set.  This method allows
1121     * modules to provide users with "read-only" access to internal sets.
1122     * Query operations on the returned set "read through" to the specified
1123     * set, and attempts to modify the returned set, whether direct or via its
1124     * iterator, result in an <tt>UnsupportedOperationException</tt>.<p>
1125     *
1126     * The returned set will be serializable if the specified set
1127     * is serializable.
1128     *
1129     * @param  s the set for which an unmodifiable view is to be returned.
1130     * @return an unmodifiable view of the specified set.
1131     */
1132    public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
1133        return new UnmodifiableSet<>(s);
1134    }
1135
1136    /**
1137     * @serial include
1138     */
1139    static class UnmodifiableSet<E> extends UnmodifiableCollection<E>
1140                                 implements Set<E>, Serializable {
1141        private static final long serialVersionUID = -9215047833775013803L;
1142
1143        UnmodifiableSet(Set<? extends E> s)     {super(s);}
1144        public boolean equals(Object o) {return o == this || c.equals(o);}
1145        public int hashCode()           {return c.hashCode();}
1146    }
1147
1148    /**
1149     * Returns an unmodifiable view of the specified sorted set.  This method
1150     * allows modules to provide users with "read-only" access to internal
1151     * sorted sets.  Query operations on the returned sorted set "read
1152     * through" to the specified sorted set.  Attempts to modify the returned
1153     * sorted set, whether direct, via its iterator, or via its
1154     * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in
1155     * an <tt>UnsupportedOperationException</tt>.<p>
1156     *
1157     * The returned sorted set will be serializable if the specified sorted set
1158     * is serializable.
1159     *
1160     * @param s the sorted set for which an unmodifiable view is to be
1161     *        returned.
1162     * @return an unmodifiable view of the specified sorted set.
1163     */
1164    public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
1165        return new UnmodifiableSortedSet<>(s);
1166    }
1167
1168    /**
1169     * @serial include
1170     */
1171    static class UnmodifiableSortedSet<E>
1172                             extends UnmodifiableSet<E>
1173                             implements SortedSet<E>, Serializable {
1174        private static final long serialVersionUID = -4929149591599911165L;
1175        private final SortedSet<E> ss;
1176
1177        UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;}
1178
1179        public Comparator<? super E> comparator() {return ss.comparator();}
1180
1181        public SortedSet<E> subSet(E fromElement, E toElement) {
1182            return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));
1183        }
1184        public SortedSet<E> headSet(E toElement) {
1185            return new UnmodifiableSortedSet<>(ss.headSet(toElement));
1186        }
1187        public SortedSet<E> tailSet(E fromElement) {
1188            return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));
1189        }
1190
1191        public E first()                   {return ss.first();}
1192        public E last()                    {return ss.last();}
1193    }
1194
1195    /**
1196     * Returns an unmodifiable view of the specified list.  This method allows
1197     * modules to provide users with "read-only" access to internal
1198     * lists.  Query operations on the returned list "read through" to the
1199     * specified list, and attempts to modify the returned list, whether
1200     * direct or via its iterator, result in an
1201     * <tt>UnsupportedOperationException</tt>.<p>
1202     *
1203     * The returned list will be serializable if the specified list
1204     * is serializable. Similarly, the returned list will implement
1205     * {@link RandomAccess} if the specified list does.
1206     *
1207     * @param  list the list for which an unmodifiable view is to be returned.
1208     * @return an unmodifiable view of the specified list.
1209     */
1210    public static <T> List<T> unmodifiableList(List<? extends T> list) {
1211        return (list instanceof RandomAccess ?
1212                new UnmodifiableRandomAccessList<>(list) :
1213                new UnmodifiableList<>(list));
1214    }
1215
1216    /**
1217     * @serial include
1218     */
1219    static class UnmodifiableList<E> extends UnmodifiableCollection<E>
1220                                  implements List<E> {
1221        private static final long serialVersionUID = -283967356065247728L;
1222        final List<? extends E> list;
1223
1224        UnmodifiableList(List<? extends E> list) {
1225            super(list);
1226            this.list = list;
1227        }
1228
1229        public boolean equals(Object o) {return o == this || list.equals(o);}
1230        public int hashCode()           {return list.hashCode();}
1231
1232        public E get(int index) {return list.get(index);}
1233        public E set(int index, E element) {
1234            throw new UnsupportedOperationException();
1235        }
1236        public void add(int index, E element) {
1237            throw new UnsupportedOperationException();
1238        }
1239        public E remove(int index) {
1240            throw new UnsupportedOperationException();
1241        }
1242        public int indexOf(Object o)            {return list.indexOf(o);}
1243        public int lastIndexOf(Object o)        {return list.lastIndexOf(o);}
1244        public boolean addAll(int index, Collection<? extends E> c) {
1245            throw new UnsupportedOperationException();
1246        }
1247        public ListIterator<E> listIterator()   {return listIterator(0);}
1248
1249        public ListIterator<E> listIterator(final int index) {
1250            return new ListIterator<E>() {
1251                private final ListIterator<? extends E> i
1252                    = list.listIterator(index);
1253
1254                public boolean hasNext()     {return i.hasNext();}
1255                public E next()              {return i.next();}
1256                public boolean hasPrevious() {return i.hasPrevious();}
1257                public E previous()          {return i.previous();}
1258                public int nextIndex()       {return i.nextIndex();}
1259                public int previousIndex()   {return i.previousIndex();}
1260
1261                public void remove() {
1262                    throw new UnsupportedOperationException();
1263                }
1264                public void set(E e) {
1265                    throw new UnsupportedOperationException();
1266                }
1267                public void add(E e) {
1268                    throw new UnsupportedOperationException();
1269                }
1270            };
1271        }
1272
1273        public List<E> subList(int fromIndex, int toIndex) {
1274            return new UnmodifiableList<>(list.subList(fromIndex, toIndex));
1275        }
1276
1277        /**
1278         * UnmodifiableRandomAccessList instances are serialized as
1279         * UnmodifiableList instances to allow them to be deserialized
1280         * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList).
1281         * This method inverts the transformation.  As a beneficial
1282         * side-effect, it also grafts the RandomAccess marker onto
1283         * UnmodifiableList instances that were serialized in pre-1.4 JREs.
1284         *
1285         * Note: Unfortunately, UnmodifiableRandomAccessList instances
1286         * serialized in 1.4.1 and deserialized in 1.4 will become
1287         * UnmodifiableList instances, as this method was missing in 1.4.
1288         */
1289        private Object readResolve() {
1290            return (list instanceof RandomAccess
1291                    ? new UnmodifiableRandomAccessList<>(list)
1292                    : this);
1293        }
1294    }
1295
1296    /**
1297     * @serial include
1298     */
1299    static class UnmodifiableRandomAccessList<E> extends UnmodifiableList<E>
1300                                              implements RandomAccess
1301    {
1302        UnmodifiableRandomAccessList(List<? extends E> list) {
1303            super(list);
1304        }
1305
1306        public List<E> subList(int fromIndex, int toIndex) {
1307            return new UnmodifiableRandomAccessList<>(
1308                list.subList(fromIndex, toIndex));
1309        }
1310
1311        private static final long serialVersionUID = -2542308836966382001L;
1312
1313        /**
1314         * Allows instances to be deserialized in pre-1.4 JREs (which do
1315         * not have UnmodifiableRandomAccessList).  UnmodifiableList has
1316         * a readResolve method that inverts this transformation upon
1317         * deserialization.
1318         */
1319        private Object writeReplace() {
1320            return new UnmodifiableList<>(list);
1321        }
1322    }
1323
1324    /**
1325     * Returns an unmodifiable view of the specified map.  This method
1326     * allows modules to provide users with "read-only" access to internal
1327     * maps.  Query operations on the returned map "read through"
1328     * to the specified map, and attempts to modify the returned
1329     * map, whether direct or via its collection views, result in an
1330     * <tt>UnsupportedOperationException</tt>.<p>
1331     *
1332     * The returned map will be serializable if the specified map
1333     * is serializable.
1334     *
1335     * @param  m the map for which an unmodifiable view is to be returned.
1336     * @return an unmodifiable view of the specified map.
1337     */
1338    public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
1339        return new UnmodifiableMap<>(m);
1340    }
1341
1342    /**
1343     * @serial include
1344     */
1345    private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
1346        private static final long serialVersionUID = -1034234728574286014L;
1347
1348        private final Map<? extends K, ? extends V> m;
1349
1350        UnmodifiableMap(Map<? extends K, ? extends V> m) {
1351            if (m==null)
1352                throw new NullPointerException();
1353            this.m = m;
1354        }
1355
1356        public int size()                        {return m.size();}
1357        public boolean isEmpty()                 {return m.isEmpty();}
1358        public boolean containsKey(Object key)   {return m.containsKey(key);}
1359        public boolean containsValue(Object val) {return m.containsValue(val);}
1360        public V get(Object key)                 {return m.get(key);}
1361
1362        public V put(K key, V value) {
1363            throw new UnsupportedOperationException();
1364        }
1365        public V remove(Object key) {
1366            throw new UnsupportedOperationException();
1367        }
1368        public void putAll(Map<? extends K, ? extends V> m) {
1369            throw new UnsupportedOperationException();
1370        }
1371        public void clear() {
1372            throw new UnsupportedOperationException();
1373        }
1374
1375        private transient Set<K> keySet = null;
1376        private transient Set<Map.Entry<K,V>> entrySet = null;
1377        private transient Collection<V> values = null;
1378
1379        public Set<K> keySet() {
1380            if (keySet==null)
1381                keySet = unmodifiableSet(m.keySet());
1382            return keySet;
1383        }
1384
1385        public Set<Map.Entry<K,V>> entrySet() {
1386            if (entrySet==null)
1387                entrySet = new UnmodifiableEntrySet<>(m.entrySet());
1388            return entrySet;
1389        }
1390
1391        public Collection<V> values() {
1392            if (values==null)
1393                values = unmodifiableCollection(m.values());
1394            return values;
1395        }
1396
1397        public boolean equals(Object o) {return o == this || m.equals(o);}
1398        public int hashCode()           {return m.hashCode();}
1399        public String toString()        {return m.toString();}
1400
1401        // Override default methods in Map
1402        @Override
1403        public void forEach(BiConsumer<? super K, ? super V> action) {
1404            m.forEach(action);
1405        }
1406
1407        /**
1408         * We need this class in addition to UnmodifiableSet as
1409         * Map.Entries themselves permit modification of the backing Map
1410         * via their setValue operation.  This class is subtle: there are
1411         * many possible attacks that must be thwarted.
1412         *
1413         * @serial include
1414         */
1415        static class UnmodifiableEntrySet<K,V>
1416            extends UnmodifiableSet<Map.Entry<K,V>> {
1417            private static final long serialVersionUID = 7854390611657943733L;
1418
1419            UnmodifiableEntrySet(Set<? extends Map.Entry<? extends K, ? extends V>> s) {
1420                super((Set)s);
1421            }
1422
1423            static <K, V> Consumer<Map.Entry<K, V>> entryConsumer(Consumer<? super Entry<K, V>> action) {
1424                return e -> action.accept(new UnmodifiableEntry<>(e));
1425            }
1426
1427            // Override default methods in Collection
1428            public void forEach(Consumer<? super Entry<K, V>> action) {
1429                Objects.requireNonNull(action);
1430                c.forEach(entryConsumer(action));
1431            }
1432
1433            public Iterator<Map.Entry<K,V>> iterator() {
1434                return new Iterator<Map.Entry<K,V>>() {
1435                    private final Iterator<? extends Map.Entry<? extends K, ? extends V>> i = c.iterator();
1436
1437                    public boolean hasNext() {
1438                        return i.hasNext();
1439                    }
1440                    public Map.Entry<K,V> next() {
1441                        return new UnmodifiableEntry<>(i.next());
1442                    }
1443                    public void remove() {
1444                        throw new UnsupportedOperationException();
1445                    }
1446                };
1447            }
1448
1449            public Object[] toArray() {
1450                Object[] a = c.toArray();
1451                for (int i=0; i<a.length; i++)
1452                    a[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)a[i]);
1453                return a;
1454            }
1455
1456            public <T> T[] toArray(T[] a) {
1457                // We don't pass a to c.toArray, to avoid window of
1458                // vulnerability wherein an unscrupulous multithreaded client
1459                // could get his hands on raw (unwrapped) Entries from c.
1460                Object[] arr = c.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
1461
1462                for (int i=0; i<arr.length; i++)
1463                    arr[i] = new UnmodifiableEntry<>((Map.Entry<K,V>)arr[i]);
1464
1465                if (arr.length > a.length)
1466                    return (T[])arr;
1467
1468                System.arraycopy(arr, 0, a, 0, arr.length);
1469                if (a.length > arr.length)
1470                    a[arr.length] = null;
1471                return a;
1472            }
1473
1474            /**
1475             * This method is overridden to protect the backing set against
1476             * an object with a nefarious equals function that senses
1477             * that the equality-candidate is Map.Entry and calls its
1478             * setValue method.
1479             */
1480            public boolean contains(Object o) {
1481                if (!(o instanceof Map.Entry))
1482                    return false;
1483                return c.contains(
1484                    new UnmodifiableEntry<>((Map.Entry<?,?>) o));
1485            }
1486
1487            /**
1488             * The next two methods are overridden to protect against
1489             * an unscrupulous List whose contains(Object o) method senses
1490             * when o is a Map.Entry, and calls o.setValue.
1491             */
1492            public boolean containsAll(Collection<?> coll) {
1493                for (Object e : coll) {
1494                    if (!contains(e)) // Invokes safe contains() above
1495                        return false;
1496                }
1497                return true;
1498            }
1499            public boolean equals(Object o) {
1500                if (o == this)
1501                    return true;
1502
1503                if (!(o instanceof Set))
1504                    return false;
1505                Set s = (Set) o;
1506                if (s.size() != c.size())
1507                    return false;
1508                return containsAll(s); // Invokes safe containsAll() above
1509            }
1510
1511            /**
1512             * This "wrapper class" serves two purposes: it prevents
1513             * the client from modifying the backing Map, by short-circuiting
1514             * the setValue method, and it protects the backing Map against
1515             * an ill-behaved Map.Entry that attempts to modify another
1516             * Map Entry when asked to perform an equality check.
1517             */
1518            private static class UnmodifiableEntry<K,V> implements Map.Entry<K,V> {
1519                private Map.Entry<? extends K, ? extends V> e;
1520
1521                UnmodifiableEntry(Map.Entry<? extends K, ? extends V> e) {this.e = e;}
1522
1523                public K getKey()        {return e.getKey();}
1524                public V getValue()      {return e.getValue();}
1525                public V setValue(V value) {
1526                    throw new UnsupportedOperationException();
1527                }
1528                public int hashCode()    {return e.hashCode();}
1529                public boolean equals(Object o) {
1530                    if (this == o)
1531                        return true;
1532                    if (!(o instanceof Map.Entry))
1533                        return false;
1534                    Map.Entry t = (Map.Entry)o;
1535                    return eq(e.getKey(),   t.getKey()) &&
1536                           eq(e.getValue(), t.getValue());
1537                }
1538                public String toString() {return e.toString();}
1539            }
1540        }
1541    }
1542
1543    /**
1544     * Returns an unmodifiable view of the specified sorted map.  This method
1545     * allows modules to provide users with "read-only" access to internal
1546     * sorted maps.  Query operations on the returned sorted map "read through"
1547     * to the specified sorted map.  Attempts to modify the returned
1548     * sorted map, whether direct, via its collection views, or via its
1549     * <tt>subMap</tt>, <tt>headMap</tt>, or <tt>tailMap</tt> views, result in
1550     * an <tt>UnsupportedOperationException</tt>.<p>
1551     *
1552     * The returned sorted map will be serializable if the specified sorted map
1553     * is serializable.
1554     *
1555     * @param m the sorted map for which an unmodifiable view is to be
1556     *        returned.
1557     * @return an unmodifiable view of the specified sorted map.
1558     */
1559    public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
1560        return new UnmodifiableSortedMap<>(m);
1561    }
1562
1563    /**
1564     * @serial include
1565     */
1566    static class UnmodifiableSortedMap<K,V>
1567          extends UnmodifiableMap<K,V>
1568          implements SortedMap<K,V>, Serializable {
1569        private static final long serialVersionUID = -8806743815996713206L;
1570
1571        private final SortedMap<K, ? extends V> sm;
1572
1573        UnmodifiableSortedMap(SortedMap<K, ? extends V> m) {super(m); sm = m;}
1574
1575        public Comparator<? super K> comparator() {return sm.comparator();}
1576
1577        public SortedMap<K,V> subMap(K fromKey, K toKey) {
1578            return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey));
1579        }
1580        public SortedMap<K,V> headMap(K toKey) {
1581            return new UnmodifiableSortedMap<>(sm.headMap(toKey));
1582        }
1583        public SortedMap<K,V> tailMap(K fromKey) {
1584            return new UnmodifiableSortedMap<>(sm.tailMap(fromKey));
1585        }
1586
1587        public K firstKey()           {return sm.firstKey();}
1588        public K lastKey()            {return sm.lastKey();}
1589    }
1590
1591
1592    // Synch Wrappers
1593
1594    /**
1595     * Returns a synchronized (thread-safe) collection backed by the specified
1596     * collection.  In order to guarantee serial access, it is critical that
1597     * <strong>all</strong> access to the backing collection is accomplished
1598     * through the returned collection.<p>
1599     *
1600     * It is imperative that the user manually synchronize on the returned
1601     * collection when iterating over it:
1602     * <pre>
1603     *  Collection c = Collections.synchronizedCollection(myCollection);
1604     *     ...
1605     *  synchronized (c) {
1606     *      Iterator i = c.iterator(); // Must be in the synchronized block
1607     *      while (i.hasNext())
1608     *         foo(i.next());
1609     *  }
1610     * </pre>
1611     * Failure to follow this advice may result in non-deterministic behavior.
1612     *
1613     * <p>The returned collection does <i>not</i> pass the <tt>hashCode</tt>
1614     * and <tt>equals</tt> operations through to the backing collection, but
1615     * relies on <tt>Object</tt>'s equals and hashCode methods.  This is
1616     * necessary to preserve the contracts of these operations in the case
1617     * that the backing collection is a set or a list.<p>
1618     *
1619     * The returned collection will be serializable if the specified collection
1620     * is serializable.
1621     *
1622     * @param  c the collection to be "wrapped" in a synchronized collection.
1623     * @return a synchronized view of the specified collection.
1624     */
1625    public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
1626        return new SynchronizedCollection<>(c);
1627    }
1628
1629    static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) {
1630        return new SynchronizedCollection<>(c, mutex);
1631    }
1632
1633    /**
1634     * @serial include
1635     */
1636    static class SynchronizedCollection<E> implements Collection<E>, Serializable {
1637        private static final long serialVersionUID = 3053995032091335093L;
1638
1639        final Collection<E> c;  // Backing Collection
1640        final Object mutex;     // Object on which to synchronize
1641
1642        SynchronizedCollection(Collection<E> c) {
1643            if (c==null)
1644                throw new NullPointerException();
1645            this.c = c;
1646            mutex = this;
1647        }
1648        SynchronizedCollection(Collection<E> c, Object mutex) {
1649            this.c = c;
1650            this.mutex = mutex;
1651        }
1652
1653        public int size() {
1654            synchronized (mutex) {return c.size();}
1655        }
1656        public boolean isEmpty() {
1657            synchronized (mutex) {return c.isEmpty();}
1658        }
1659        public boolean contains(Object o) {
1660            synchronized (mutex) {return c.contains(o);}
1661        }
1662        public Object[] toArray() {
1663            synchronized (mutex) {return c.toArray();}
1664        }
1665        public <T> T[] toArray(T[] a) {
1666            synchronized (mutex) {return c.toArray(a);}
1667        }
1668
1669        public Iterator<E> iterator() {
1670            return c.iterator(); // Must be manually synched by user!
1671        }
1672
1673        public boolean add(E e) {
1674            synchronized (mutex) {return c.add(e);}
1675        }
1676        public boolean remove(Object o) {
1677            synchronized (mutex) {return c.remove(o);}
1678        }
1679
1680        public boolean containsAll(Collection<?> coll) {
1681            synchronized (mutex) {return c.containsAll(coll);}
1682        }
1683        public boolean addAll(Collection<? extends E> coll) {
1684            synchronized (mutex) {return c.addAll(coll);}
1685        }
1686        public boolean removeAll(Collection<?> coll) {
1687            synchronized (mutex) {return c.removeAll(coll);}
1688        }
1689        public boolean retainAll(Collection<?> coll) {
1690            synchronized (mutex) {return c.retainAll(coll);}
1691        }
1692        public void clear() {
1693            synchronized (mutex) {c.clear();}
1694        }
1695        public String toString() {
1696            synchronized (mutex) {return c.toString();}
1697        }
1698
1699        // Override default methods in Collection
1700        @Override
1701        public void forEach(Consumer<? super E> consumer) {
1702            synchronized (mutex) {c.forEach(consumer);}
1703        }
1704
1705        private void writeObject(ObjectOutputStream s) throws IOException {
1706            synchronized (mutex) {s.defaultWriteObject();}
1707        }
1708    }
1709
1710    /**
1711     * Returns a synchronized (thread-safe) set backed by the specified
1712     * set.  In order to guarantee serial access, it is critical that
1713     * <strong>all</strong> access to the backing set is accomplished
1714     * through the returned set.<p>
1715     *
1716     * It is imperative that the user manually synchronize on the returned
1717     * set when iterating over it:
1718     * <pre>
1719     *  Set s = Collections.synchronizedSet(new HashSet());
1720     *      ...
1721     *  synchronized (s) {
1722     *      Iterator i = s.iterator(); // Must be in the synchronized block
1723     *      while (i.hasNext())
1724     *          foo(i.next());
1725     *  }
1726     * </pre>
1727     * Failure to follow this advice may result in non-deterministic behavior.
1728     *
1729     * <p>The returned set will be serializable if the specified set is
1730     * serializable.
1731     *
1732     * @param  s the set to be "wrapped" in a synchronized set.
1733     * @return a synchronized view of the specified set.
1734     */
1735    public static <T> Set<T> synchronizedSet(Set<T> s) {
1736        return new SynchronizedSet<>(s);
1737    }
1738
1739    static <T> Set<T> synchronizedSet(Set<T> s, Object mutex) {
1740        return new SynchronizedSet<>(s, mutex);
1741    }
1742
1743    /**
1744     * @serial include
1745     */
1746    static class SynchronizedSet<E>
1747          extends SynchronizedCollection<E>
1748          implements Set<E> {
1749        private static final long serialVersionUID = 487447009682186044L;
1750
1751        SynchronizedSet(Set<E> s) {
1752            super(s);
1753        }
1754        SynchronizedSet(Set<E> s, Object mutex) {
1755            super(s, mutex);
1756        }
1757
1758        public boolean equals(Object o) {
1759            if (this == o)
1760                return true;
1761            synchronized (mutex) {return c.equals(o);}
1762        }
1763        public int hashCode() {
1764            synchronized (mutex) {return c.hashCode();}
1765        }
1766    }
1767
1768    /**
1769     * Returns a synchronized (thread-safe) sorted set backed by the specified
1770     * sorted set.  In order to guarantee serial access, it is critical that
1771     * <strong>all</strong> access to the backing sorted set is accomplished
1772     * through the returned sorted set (or its views).<p>
1773     *
1774     * It is imperative that the user manually synchronize on the returned
1775     * sorted set when iterating over it or any of its <tt>subSet</tt>,
1776     * <tt>headSet</tt>, or <tt>tailSet</tt> views.
1777     * <pre>
1778     *  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
1779     *      ...
1780     *  synchronized (s) {
1781     *      Iterator i = s.iterator(); // Must be in the synchronized block
1782     *      while (i.hasNext())
1783     *          foo(i.next());
1784     *  }
1785     * </pre>
1786     * or:
1787     * <pre>
1788     *  SortedSet s = Collections.synchronizedSortedSet(new TreeSet());
1789     *  SortedSet s2 = s.headSet(foo);
1790     *      ...
1791     *  synchronized (s) {  // Note: s, not s2!!!
1792     *      Iterator i = s2.iterator(); // Must be in the synchronized block
1793     *      while (i.hasNext())
1794     *          foo(i.next());
1795     *  }
1796     * </pre>
1797     * Failure to follow this advice may result in non-deterministic behavior.
1798     *
1799     * <p>The returned sorted set will be serializable if the specified
1800     * sorted set is serializable.
1801     *
1802     * @param  s the sorted set to be "wrapped" in a synchronized sorted set.
1803     * @return a synchronized view of the specified sorted set.
1804     */
1805    public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) {
1806        return new SynchronizedSortedSet<>(s);
1807    }
1808
1809    /**
1810     * @serial include
1811     */
1812    static class SynchronizedSortedSet<E>
1813        extends SynchronizedSet<E>
1814        implements SortedSet<E>
1815    {
1816        private static final long serialVersionUID = 8695801310862127406L;
1817
1818        private final SortedSet<E> ss;
1819
1820        SynchronizedSortedSet(SortedSet<E> s) {
1821            super(s);
1822            ss = s;
1823        }
1824        SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
1825            super(s, mutex);
1826            ss = s;
1827        }
1828
1829        public Comparator<? super E> comparator() {
1830            synchronized (mutex) {return ss.comparator();}
1831        }
1832
1833        public SortedSet<E> subSet(E fromElement, E toElement) {
1834            synchronized (mutex) {
1835                return new SynchronizedSortedSet<>(
1836                    ss.subSet(fromElement, toElement), mutex);
1837            }
1838        }
1839        public SortedSet<E> headSet(E toElement) {
1840            synchronized (mutex) {
1841                return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
1842            }
1843        }
1844        public SortedSet<E> tailSet(E fromElement) {
1845            synchronized (mutex) {
1846               return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
1847            }
1848        }
1849
1850        public E first() {
1851            synchronized (mutex) {return ss.first();}
1852        }
1853        public E last() {
1854            synchronized (mutex) {return ss.last();}
1855        }
1856    }
1857
1858    /**
1859     * Returns a synchronized (thread-safe) list backed by the specified
1860     * list.  In order to guarantee serial access, it is critical that
1861     * <strong>all</strong> access to the backing list is accomplished
1862     * through the returned list.<p>
1863     *
1864     * It is imperative that the user manually synchronize on the returned
1865     * list when iterating over it:
1866     * <pre>
1867     *  List list = Collections.synchronizedList(new ArrayList());
1868     *      ...
1869     *  synchronized (list) {
1870     *      Iterator i = list.iterator(); // Must be in synchronized block
1871     *      while (i.hasNext())
1872     *          foo(i.next());
1873     *  }
1874     * </pre>
1875     * Failure to follow this advice may result in non-deterministic behavior.
1876     *
1877     * <p>The returned list will be serializable if the specified list is
1878     * serializable.
1879     *
1880     * @param  list the list to be "wrapped" in a synchronized list.
1881     * @return a synchronized view of the specified list.
1882     */
1883    public static <T> List<T> synchronizedList(List<T> list) {
1884        return (list instanceof RandomAccess ?
1885                new SynchronizedRandomAccessList<>(list) :
1886                new SynchronizedList<>(list));
1887    }
1888
1889    static <T> List<T> synchronizedList(List<T> list, Object mutex) {
1890        return (list instanceof RandomAccess ?
1891                new SynchronizedRandomAccessList<>(list, mutex) :
1892                new SynchronizedList<>(list, mutex));
1893    }
1894
1895    /**
1896     * @serial include
1897     */
1898    static class SynchronizedList<E>
1899        extends SynchronizedCollection<E>
1900        implements List<E> {
1901        private static final long serialVersionUID = -7754090372962971524L;
1902
1903        final List<E> list;
1904
1905        SynchronizedList(List<E> list) {
1906            super(list);
1907            this.list = list;
1908        }
1909        SynchronizedList(List<E> list, Object mutex) {
1910            super(list, mutex);
1911            this.list = list;
1912        }
1913
1914        public boolean equals(Object o) {
1915            if (this == o)
1916                return true;
1917            synchronized (mutex) {return list.equals(o);}
1918        }
1919        public int hashCode() {
1920            synchronized (mutex) {return list.hashCode();}
1921        }
1922
1923        public E get(int index) {
1924            synchronized (mutex) {return list.get(index);}
1925        }
1926        public E set(int index, E element) {
1927            synchronized (mutex) {return list.set(index, element);}
1928        }
1929        public void add(int index, E element) {
1930            synchronized (mutex) {list.add(index, element);}
1931        }
1932        public E remove(int index) {
1933            synchronized (mutex) {return list.remove(index);}
1934        }
1935
1936        public int indexOf(Object o) {
1937            synchronized (mutex) {return list.indexOf(o);}
1938        }
1939        public int lastIndexOf(Object o) {
1940            synchronized (mutex) {return list.lastIndexOf(o);}
1941        }
1942
1943        public boolean addAll(int index, Collection<? extends E> c) {
1944            synchronized (mutex) {return list.addAll(index, c);}
1945        }
1946
1947        public ListIterator<E> listIterator() {
1948            return list.listIterator(); // Must be manually synched by user
1949        }
1950
1951        public ListIterator<E> listIterator(int index) {
1952            return list.listIterator(index); // Must be manually synched by user
1953        }
1954
1955        public List<E> subList(int fromIndex, int toIndex) {
1956            synchronized (mutex) {
1957                return new SynchronizedList<>(list.subList(fromIndex, toIndex),
1958                                            mutex);
1959            }
1960        }
1961
1962        /**
1963         * SynchronizedRandomAccessList instances are serialized as
1964         * SynchronizedList instances to allow them to be deserialized
1965         * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList).
1966         * This method inverts the transformation.  As a beneficial
1967         * side-effect, it also grafts the RandomAccess marker onto
1968         * SynchronizedList instances that were serialized in pre-1.4 JREs.
1969         *
1970         * Note: Unfortunately, SynchronizedRandomAccessList instances
1971         * serialized in 1.4.1 and deserialized in 1.4 will become
1972         * SynchronizedList instances, as this method was missing in 1.4.
1973         */
1974        private Object readResolve() {
1975            return (list instanceof RandomAccess
1976                    ? new SynchronizedRandomAccessList<>(list)
1977                    : this);
1978        }
1979    }
1980
1981    /**
1982     * @serial include
1983     */
1984    static class SynchronizedRandomAccessList<E>
1985        extends SynchronizedList<E>
1986        implements RandomAccess {
1987
1988        SynchronizedRandomAccessList(List<E> list) {
1989            super(list);
1990        }
1991
1992        SynchronizedRandomAccessList(List<E> list, Object mutex) {
1993            super(list, mutex);
1994        }
1995
1996        public List<E> subList(int fromIndex, int toIndex) {
1997            synchronized (mutex) {
1998                return new SynchronizedRandomAccessList<>(
1999                    list.subList(fromIndex, toIndex), mutex);
2000            }
2001        }
2002
2003        private static final long serialVersionUID = 1530674583602358482L;
2004
2005        /**
2006         * Allows instances to be deserialized in pre-1.4 JREs (which do
2007         * not have SynchronizedRandomAccessList).  SynchronizedList has
2008         * a readResolve method that inverts this transformation upon
2009         * deserialization.
2010         */
2011        private Object writeReplace() {
2012            return new SynchronizedList<>(list);
2013        }
2014    }
2015
2016    /**
2017     * Returns a synchronized (thread-safe) map backed by the specified
2018     * map.  In order to guarantee serial access, it is critical that
2019     * <strong>all</strong> access to the backing map is accomplished
2020     * through the returned map.<p>
2021     *
2022     * It is imperative that the user manually synchronize on the returned
2023     * map when iterating over any of its collection views:
2024     * <pre>
2025     *  Map m = Collections.synchronizedMap(new HashMap());
2026     *      ...
2027     *  Set s = m.keySet();  // Needn't be in synchronized block
2028     *      ...
2029     *  synchronized (m) {  // Synchronizing on m, not s!
2030     *      Iterator i = s.iterator(); // Must be in synchronized block
2031     *      while (i.hasNext())
2032     *          foo(i.next());
2033     *  }
2034     * </pre>
2035     * Failure to follow this advice may result in non-deterministic behavior.
2036     *
2037     * <p>The returned map will be serializable if the specified map is
2038     * serializable.
2039     *
2040     * @param  m the map to be "wrapped" in a synchronized map.
2041     * @return a synchronized view of the specified map.
2042     */
2043    public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
2044        return new SynchronizedMap<>(m);
2045    }
2046
2047    /**
2048     * @serial include
2049     */
2050    private static class SynchronizedMap<K,V>
2051        implements Map<K,V>, Serializable {
2052        private static final long serialVersionUID = 1978198479659022715L;
2053
2054        private final Map<K,V> m;     // Backing Map
2055        final Object      mutex;        // Object on which to synchronize
2056
2057        SynchronizedMap(Map<K,V> m) {
2058            if (m==null)
2059                throw new NullPointerException();
2060            this.m = m;
2061            mutex = this;
2062        }
2063
2064        SynchronizedMap(Map<K,V> m, Object mutex) {
2065            this.m = m;
2066            this.mutex = mutex;
2067        }
2068
2069        public int size() {
2070            synchronized (mutex) {return m.size();}
2071        }
2072        public boolean isEmpty() {
2073            synchronized (mutex) {return m.isEmpty();}
2074        }
2075        public boolean containsKey(Object key) {
2076            synchronized (mutex) {return m.containsKey(key);}
2077        }
2078        public boolean containsValue(Object value) {
2079            synchronized (mutex) {return m.containsValue(value);}
2080        }
2081        public V get(Object key) {
2082            synchronized (mutex) {return m.get(key);}
2083        }
2084
2085        public V put(K key, V value) {
2086            synchronized (mutex) {return m.put(key, value);}
2087        }
2088        public V remove(Object key) {
2089            synchronized (mutex) {return m.remove(key);}
2090        }
2091        public void putAll(Map<? extends K, ? extends V> map) {
2092            synchronized (mutex) {m.putAll(map);}
2093        }
2094        public void clear() {
2095            synchronized (mutex) {m.clear();}
2096        }
2097
2098        private transient Set<K> keySet = null;
2099        private transient Set<Map.Entry<K,V>> entrySet = null;
2100        private transient Collection<V> values = null;
2101
2102        public Set<K> keySet() {
2103            synchronized (mutex) {
2104                if (keySet==null)
2105                    keySet = new SynchronizedSet<>(m.keySet(), mutex);
2106                return keySet;
2107            }
2108        }
2109
2110        public Set<Map.Entry<K,V>> entrySet() {
2111            synchronized (mutex) {
2112                if (entrySet==null)
2113                    entrySet = new SynchronizedSet<>(m.entrySet(), mutex);
2114                return entrySet;
2115            }
2116        }
2117
2118        public Collection<V> values() {
2119            synchronized (mutex) {
2120                if (values==null)
2121                    values = new SynchronizedCollection<>(m.values(), mutex);
2122                return values;
2123            }
2124        }
2125
2126        public boolean equals(Object o) {
2127            if (this == o)
2128                return true;
2129            synchronized (mutex) {return m.equals(o);}
2130        }
2131        public int hashCode() {
2132            synchronized (mutex) {return m.hashCode();}
2133        }
2134        public String toString() {
2135            synchronized (mutex) {return m.toString();}
2136        }
2137        // Override default methods in Map
2138        @Override
2139        public void forEach(BiConsumer<? super K, ? super V> action) {
2140            synchronized (mutex) {m.forEach(action);}
2141        }
2142
2143        private void writeObject(ObjectOutputStream s) throws IOException {
2144            synchronized (mutex) {s.defaultWriteObject();}
2145        }
2146    }
2147
2148    /**
2149     * Returns a synchronized (thread-safe) sorted map backed by the specified
2150     * sorted map.  In order to guarantee serial access, it is critical that
2151     * <strong>all</strong> access to the backing sorted map is accomplished
2152     * through the returned sorted map (or its views).<p>
2153     *
2154     * It is imperative that the user manually synchronize on the returned
2155     * sorted map when iterating over any of its collection views, or the
2156     * collections views of any of its <tt>subMap</tt>, <tt>headMap</tt> or
2157     * <tt>tailMap</tt> views.
2158     * <pre>
2159     *  SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2160     *      ...
2161     *  Set s = m.keySet();  // Needn't be in synchronized block
2162     *      ...
2163     *  synchronized (m) {  // Synchronizing on m, not s!
2164     *      Iterator i = s.iterator(); // Must be in synchronized block
2165     *      while (i.hasNext())
2166     *          foo(i.next());
2167     *  }
2168     * </pre>
2169     * or:
2170     * <pre>
2171     *  SortedMap m = Collections.synchronizedSortedMap(new TreeMap());
2172     *  SortedMap m2 = m.subMap(foo, bar);
2173     *      ...
2174     *  Set s2 = m2.keySet();  // Needn't be in synchronized block
2175     *      ...
2176     *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
2177     *      Iterator i = s.iterator(); // Must be in synchronized block
2178     *      while (i.hasNext())
2179     *          foo(i.next());
2180     *  }
2181     * </pre>
2182     * Failure to follow this advice may result in non-deterministic behavior.
2183     *
2184     * <p>The returned sorted map will be serializable if the specified
2185     * sorted map is serializable.
2186     *
2187     * @param  m the sorted map to be "wrapped" in a synchronized sorted map.
2188     * @return a synchronized view of the specified sorted map.
2189     */
2190    public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) {
2191        return new SynchronizedSortedMap<>(m);
2192    }
2193
2194
2195    /**
2196     * @serial include
2197     */
2198    static class SynchronizedSortedMap<K,V>
2199        extends SynchronizedMap<K,V>
2200        implements SortedMap<K,V>
2201    {
2202        private static final long serialVersionUID = -8798146769416483793L;
2203
2204        private final SortedMap<K,V> sm;
2205
2206        SynchronizedSortedMap(SortedMap<K,V> m) {
2207            super(m);
2208            sm = m;
2209        }
2210        SynchronizedSortedMap(SortedMap<K,V> m, Object mutex) {
2211            super(m, mutex);
2212            sm = m;
2213        }
2214
2215        public Comparator<? super K> comparator() {
2216            synchronized (mutex) {return sm.comparator();}
2217        }
2218
2219        public SortedMap<K,V> subMap(K fromKey, K toKey) {
2220            synchronized (mutex) {
2221                return new SynchronizedSortedMap<>(
2222                    sm.subMap(fromKey, toKey), mutex);
2223            }
2224        }
2225        public SortedMap<K,V> headMap(K toKey) {
2226            synchronized (mutex) {
2227                return new SynchronizedSortedMap<>(sm.headMap(toKey), mutex);
2228            }
2229        }
2230        public SortedMap<K,V> tailMap(K fromKey) {
2231            synchronized (mutex) {
2232               return new SynchronizedSortedMap<>(sm.tailMap(fromKey),mutex);
2233            }
2234        }
2235
2236        public K firstKey() {
2237            synchronized (mutex) {return sm.firstKey();}
2238        }
2239        public K lastKey() {
2240            synchronized (mutex) {return sm.lastKey();}
2241        }
2242    }
2243
2244    // Dynamically typesafe collection wrappers
2245
2246    /**
2247     * Returns a dynamically typesafe view of the specified collection.
2248     * Any attempt to insert an element of the wrong type will result in an
2249     * immediate {@link ClassCastException}.  Assuming a collection
2250     * contains no incorrectly typed elements prior to the time a
2251     * dynamically typesafe view is generated, and that all subsequent
2252     * access to the collection takes place through the view, it is
2253     * <i>guaranteed</i> that the collection cannot contain an incorrectly
2254     * typed element.
2255     *
2256     * <p>The generics mechanism in the language provides compile-time
2257     * (static) type checking, but it is possible to defeat this mechanism
2258     * with unchecked casts.  Usually this is not a problem, as the compiler
2259     * issues warnings on all such unchecked operations.  There are, however,
2260     * times when static type checking alone is not sufficient.  For example,
2261     * suppose a collection is passed to a third-party library and it is
2262     * imperative that the library code not corrupt the collection by
2263     * inserting an element of the wrong type.
2264     *
2265     * <p>Another use of dynamically typesafe views is debugging.  Suppose a
2266     * program fails with a {@code ClassCastException}, indicating that an
2267     * incorrectly typed element was put into a parameterized collection.
2268     * Unfortunately, the exception can occur at any time after the erroneous
2269     * element is inserted, so it typically provides little or no information
2270     * as to the real source of the problem.  If the problem is reproducible,
2271     * one can quickly determine its source by temporarily modifying the
2272     * program to wrap the collection with a dynamically typesafe view.
2273     * For example, this declaration:
2274     *  <pre> {@code
2275     *     Collection<String> c = new HashSet<String>();
2276     * }</pre>
2277     * may be replaced temporarily by this one:
2278     *  <pre> {@code
2279     *     Collection<String> c = Collections.checkedCollection(
2280     *         new HashSet<String>(), String.class);
2281     * }</pre>
2282     * Running the program again will cause it to fail at the point where
2283     * an incorrectly typed element is inserted into the collection, clearly
2284     * identifying the source of the problem.  Once the problem is fixed, the
2285     * modified declaration may be reverted back to the original.
2286     *
2287     * <p>The returned collection does <i>not</i> pass the hashCode and equals
2288     * operations through to the backing collection, but relies on
2289     * {@code Object}'s {@code equals} and {@code hashCode} methods.  This
2290     * is necessary to preserve the contracts of these operations in the case
2291     * that the backing collection is a set or a list.
2292     *
2293     * <p>The returned collection will be serializable if the specified
2294     * collection is serializable.
2295     *
2296     * <p>Since {@code null} is considered to be a value of any reference
2297     * type, the returned collection permits insertion of null elements
2298     * whenever the backing collection does.
2299     *
2300     * @param c the collection for which a dynamically typesafe view is to be
2301     *          returned
2302     * @param type the type of element that {@code c} is permitted to hold
2303     * @return a dynamically typesafe view of the specified collection
2304     * @since 1.5
2305     */
2306    public static <E> Collection<E> checkedCollection(Collection<E> c,
2307                                                      Class<E> type) {
2308        return new CheckedCollection<>(c, type);
2309    }
2310
2311    @SuppressWarnings("unchecked")
2312    static <T> T[] zeroLengthArray(Class<T> type) {
2313        return (T[]) Array.newInstance(type, 0);
2314    }
2315
2316    /**
2317     * @serial include
2318     */
2319    static class CheckedCollection<E> implements Collection<E>, Serializable {
2320        private static final long serialVersionUID = 1578914078182001775L;
2321
2322        final Collection<E> c;
2323        final Class<E> type;
2324
2325        void typeCheck(Object o) {
2326            if (o != null && !type.isInstance(o))
2327                throw new ClassCastException(badElementMsg(o));
2328        }
2329
2330        private String badElementMsg(Object o) {
2331            return "Attempt to insert " + o.getClass() +
2332                " element into collection with element type " + type;
2333        }
2334
2335        CheckedCollection(Collection<E> c, Class<E> type) {
2336            if (c==null || type == null)
2337                throw new NullPointerException();
2338            this.c = c;
2339            this.type = type;
2340        }
2341
2342        public int size()                 { return c.size(); }
2343        public boolean isEmpty()          { return c.isEmpty(); }
2344        public boolean contains(Object o) { return c.contains(o); }
2345        public Object[] toArray()         { return c.toArray(); }
2346        public <T> T[] toArray(T[] a)     { return c.toArray(a); }
2347        public String toString()          { return c.toString(); }
2348        public boolean remove(Object o)   { return c.remove(o); }
2349        public void clear()               {        c.clear(); }
2350
2351        public boolean containsAll(Collection<?> coll) {
2352            return c.containsAll(coll);
2353        }
2354        public boolean removeAll(Collection<?> coll) {
2355            return c.removeAll(coll);
2356        }
2357        public boolean retainAll(Collection<?> coll) {
2358            return c.retainAll(coll);
2359        }
2360
2361        public Iterator<E> iterator() {
2362            final Iterator<E> it = c.iterator();
2363            return new Iterator<E>() {
2364                public boolean hasNext() { return it.hasNext(); }
2365                public E next()          { return it.next(); }
2366                public void remove()     {        it.remove(); }};
2367        }
2368
2369        public boolean add(E e) {
2370            typeCheck(e);
2371            return c.add(e);
2372        }
2373
2374        private E[] zeroLengthElementArray = null; // Lazily initialized
2375
2376        private E[] zeroLengthElementArray() {
2377            return zeroLengthElementArray != null ? zeroLengthElementArray :
2378                (zeroLengthElementArray = zeroLengthArray(type));
2379        }
2380
2381        @SuppressWarnings("unchecked")
2382        Collection<E> checkedCopyOf(Collection<? extends E> coll) {
2383            Object[] a = null;
2384            try {
2385                E[] z = zeroLengthElementArray();
2386                a = coll.toArray(z);
2387                // Defend against coll violating the toArray contract
2388                if (a.getClass() != z.getClass())
2389                    a = Arrays.copyOf(a, a.length, z.getClass());
2390            } catch (ArrayStoreException ignore) {
2391                // To get better and consistent diagnostics,
2392                // we call typeCheck explicitly on each element.
2393                // We call clone() to defend against coll retaining a
2394                // reference to the returned array and storing a bad
2395                // element into it after it has been type checked.
2396                a = coll.toArray().clone();
2397                for (Object o : a)
2398                    typeCheck(o);
2399            }
2400            // A slight abuse of the type system, but safe here.
2401            return (Collection<E>) Arrays.asList(a);
2402        }
2403
2404        public boolean addAll(Collection<? extends E> coll) {
2405            // Doing things this way insulates us from concurrent changes
2406            // in the contents of coll and provides all-or-nothing
2407            // semantics (which we wouldn't get if we type-checked each
2408            // element as we added it)
2409            return c.addAll(checkedCopyOf(coll));
2410        }
2411
2412        // Override default methods in Collection
2413        @Override
2414        public void forEach(Consumer<? super E> action) {c.forEach(action);}
2415    }
2416
2417    /**
2418     * Returns a dynamically typesafe view of the specified set.
2419     * Any attempt to insert an element of the wrong type will result in
2420     * an immediate {@link ClassCastException}.  Assuming a set contains
2421     * no incorrectly typed elements prior to the time a dynamically typesafe
2422     * view is generated, and that all subsequent access to the set
2423     * takes place through the view, it is <i>guaranteed</i> that the
2424     * set cannot contain an incorrectly typed element.
2425     *
2426     * <p>A discussion of the use of dynamically typesafe views may be
2427     * found in the documentation for the {@link #checkedCollection
2428     * checkedCollection} method.
2429     *
2430     * <p>The returned set will be serializable if the specified set is
2431     * serializable.
2432     *
2433     * <p>Since {@code null} is considered to be a value of any reference
2434     * type, the returned set permits insertion of null elements whenever
2435     * the backing set does.
2436     *
2437     * @param s the set for which a dynamically typesafe view is to be
2438     *          returned
2439     * @param type the type of element that {@code s} is permitted to hold
2440     * @return a dynamically typesafe view of the specified set
2441     * @since 1.5
2442     */
2443    public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) {
2444        return new CheckedSet<>(s, type);
2445    }
2446
2447    /**
2448     * @serial include
2449     */
2450    static class CheckedSet<E> extends CheckedCollection<E>
2451                                 implements Set<E>, Serializable
2452    {
2453        private static final long serialVersionUID = 4694047833775013803L;
2454
2455        CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); }
2456
2457        public boolean equals(Object o) { return o == this || c.equals(o); }
2458        public int hashCode()           { return c.hashCode(); }
2459    }
2460
2461    /**
2462     * Returns a dynamically typesafe view of the specified sorted set.
2463     * Any attempt to insert an element of the wrong type will result in an
2464     * immediate {@link ClassCastException}.  Assuming a sorted set
2465     * contains no incorrectly typed elements prior to the time a
2466     * dynamically typesafe view is generated, and that all subsequent
2467     * access to the sorted set takes place through the view, it is
2468     * <i>guaranteed</i> that the sorted set cannot contain an incorrectly
2469     * typed element.
2470     *
2471     * <p>A discussion of the use of dynamically typesafe views may be
2472     * found in the documentation for the {@link #checkedCollection
2473     * checkedCollection} method.
2474     *
2475     * <p>The returned sorted set will be serializable if the specified sorted
2476     * set is serializable.
2477     *
2478     * <p>Since {@code null} is considered to be a value of any reference
2479     * type, the returned sorted set permits insertion of null elements
2480     * whenever the backing sorted set does.
2481     *
2482     * @param s the sorted set for which a dynamically typesafe view is to be
2483     *          returned
2484     * @param type the type of element that {@code s} is permitted to hold
2485     * @return a dynamically typesafe view of the specified sorted set
2486     * @since 1.5
2487     */
2488    public static <E> SortedSet<E> checkedSortedSet(SortedSet<E> s,
2489                                                    Class<E> type) {
2490        return new CheckedSortedSet<>(s, type);
2491    }
2492
2493    /**
2494     * @serial include
2495     */
2496    static class CheckedSortedSet<E> extends CheckedSet<E>
2497        implements SortedSet<E>, Serializable
2498    {
2499        private static final long serialVersionUID = 1599911165492914959L;
2500        private final SortedSet<E> ss;
2501
2502        CheckedSortedSet(SortedSet<E> s, Class<E> type) {
2503            super(s, type);
2504            ss = s;
2505        }
2506
2507        public Comparator<? super E> comparator() { return ss.comparator(); }
2508        public E first()                   { return ss.first(); }
2509        public E last()                    { return ss.last(); }
2510
2511        public SortedSet<E> subSet(E fromElement, E toElement) {
2512            return checkedSortedSet(ss.subSet(fromElement,toElement), type);
2513        }
2514        public SortedSet<E> headSet(E toElement) {
2515            return checkedSortedSet(ss.headSet(toElement), type);
2516        }
2517        public SortedSet<E> tailSet(E fromElement) {
2518            return checkedSortedSet(ss.tailSet(fromElement), type);
2519        }
2520    }
2521
2522    /**
2523     * Returns a dynamically typesafe view of the specified list.
2524     * Any attempt to insert an element of the wrong type will result in
2525     * an immediate {@link ClassCastException}.  Assuming a list contains
2526     * no incorrectly typed elements prior to the time a dynamically typesafe
2527     * view is generated, and that all subsequent access to the list
2528     * takes place through the view, it is <i>guaranteed</i> that the
2529     * list cannot contain an incorrectly typed element.
2530     *
2531     * <p>A discussion of the use of dynamically typesafe views may be
2532     * found in the documentation for the {@link #checkedCollection
2533     * checkedCollection} method.
2534     *
2535     * <p>The returned list will be serializable if the specified list
2536     * is serializable.
2537     *
2538     * <p>Since {@code null} is considered to be a value of any reference
2539     * type, the returned list permits insertion of null elements whenever
2540     * the backing list does.
2541     *
2542     * @param list the list for which a dynamically typesafe view is to be
2543     *             returned
2544     * @param type the type of element that {@code list} is permitted to hold
2545     * @return a dynamically typesafe view of the specified list
2546     * @since 1.5
2547     */
2548    public static <E> List<E> checkedList(List<E> list, Class<E> type) {
2549        return (list instanceof RandomAccess ?
2550                new CheckedRandomAccessList<>(list, type) :
2551                new CheckedList<>(list, type));
2552    }
2553
2554    /**
2555     * @serial include
2556     */
2557    static class CheckedList<E>
2558        extends CheckedCollection<E>
2559        implements List<E>
2560    {
2561        private static final long serialVersionUID = 65247728283967356L;
2562        final List<E> list;
2563
2564        CheckedList(List<E> list, Class<E> type) {
2565            super(list, type);
2566            this.list = list;
2567        }
2568
2569        public boolean equals(Object o)  { return o == this || list.equals(o); }
2570        public int hashCode()            { return list.hashCode(); }
2571        public E get(int index)          { return list.get(index); }
2572        public E remove(int index)       { return list.remove(index); }
2573        public int indexOf(Object o)     { return list.indexOf(o); }
2574        public int lastIndexOf(Object o) { return list.lastIndexOf(o); }
2575
2576        public E set(int index, E element) {
2577            typeCheck(element);
2578            return list.set(index, element);
2579        }
2580
2581        public void add(int index, E element) {
2582            typeCheck(element);
2583            list.add(index, element);
2584        }
2585
2586        public boolean addAll(int index, Collection<? extends E> c) {
2587            return list.addAll(index, checkedCopyOf(c));
2588        }
2589        public ListIterator<E> listIterator()   { return listIterator(0); }
2590
2591        public ListIterator<E> listIterator(final int index) {
2592            final ListIterator<E> i = list.listIterator(index);
2593
2594            return new ListIterator<E>() {
2595                public boolean hasNext()     { return i.hasNext(); }
2596                public E next()              { return i.next(); }
2597                public boolean hasPrevious() { return i.hasPrevious(); }
2598                public E previous()          { return i.previous(); }
2599                public int nextIndex()       { return i.nextIndex(); }
2600                public int previousIndex()   { return i.previousIndex(); }
2601                public void remove()         {        i.remove(); }
2602
2603                public void set(E e) {
2604                    typeCheck(e);
2605                    i.set(e);
2606                }
2607
2608                public void add(E e) {
2609                    typeCheck(e);
2610                    i.add(e);
2611                }
2612            };
2613        }
2614
2615        public List<E> subList(int fromIndex, int toIndex) {
2616            return new CheckedList<>(list.subList(fromIndex, toIndex), type);
2617        }
2618    }
2619
2620    /**
2621     * @serial include
2622     */
2623    static class CheckedRandomAccessList<E> extends CheckedList<E>
2624                                            implements RandomAccess
2625    {
2626        private static final long serialVersionUID = 1638200125423088369L;
2627
2628        CheckedRandomAccessList(List<E> list, Class<E> type) {
2629            super(list, type);
2630        }
2631
2632        public List<E> subList(int fromIndex, int toIndex) {
2633            return new CheckedRandomAccessList<>(
2634                list.subList(fromIndex, toIndex), type);
2635        }
2636    }
2637
2638    /**
2639     * Returns a dynamically typesafe view of the specified map.
2640     * Any attempt to insert a mapping whose key or value have the wrong
2641     * type will result in an immediate {@link ClassCastException}.
2642     * Similarly, any attempt to modify the value currently associated with
2643     * a key will result in an immediate {@link ClassCastException},
2644     * whether the modification is attempted directly through the map
2645     * itself, or through a {@link Map.Entry} instance obtained from the
2646     * map's {@link Map#entrySet() entry set} view.
2647     *
2648     * <p>Assuming a map contains no incorrectly typed keys or values
2649     * prior to the time a dynamically typesafe view is generated, and
2650     * that all subsequent access to the map takes place through the view
2651     * (or one of its collection views), it is <i>guaranteed</i> that the
2652     * map cannot contain an incorrectly typed key or value.
2653     *
2654     * <p>A discussion of the use of dynamically typesafe views may be
2655     * found in the documentation for the {@link #checkedCollection
2656     * checkedCollection} method.
2657     *
2658     * <p>The returned map will be serializable if the specified map is
2659     * serializable.
2660     *
2661     * <p>Since {@code null} is considered to be a value of any reference
2662     * type, the returned map permits insertion of null keys or values
2663     * whenever the backing map does.
2664     *
2665     * @param m the map for which a dynamically typesafe view is to be
2666     *          returned
2667     * @param keyType the type of key that {@code m} is permitted to hold
2668     * @param valueType the type of value that {@code m} is permitted to hold
2669     * @return a dynamically typesafe view of the specified map
2670     * @since 1.5
2671     */
2672    public static <K, V> Map<K, V> checkedMap(Map<K, V> m,
2673                                              Class<K> keyType,
2674                                              Class<V> valueType) {
2675        return new CheckedMap<>(m, keyType, valueType);
2676    }
2677
2678
2679    /**
2680     * @serial include
2681     */
2682    private static class CheckedMap<K,V>
2683        implements Map<K,V>, Serializable
2684    {
2685        private static final long serialVersionUID = 5742860141034234728L;
2686
2687        private final Map<K, V> m;
2688        final Class<K> keyType;
2689        final Class<V> valueType;
2690
2691        private void typeCheck(Object key, Object value) {
2692            if (key != null && !keyType.isInstance(key))
2693                throw new ClassCastException(badKeyMsg(key));
2694
2695            if (value != null && !valueType.isInstance(value))
2696                throw new ClassCastException(badValueMsg(value));
2697        }
2698
2699        private String badKeyMsg(Object key) {
2700            return "Attempt to insert " + key.getClass() +
2701                " key into map with key type " + keyType;
2702        }
2703
2704        private String badValueMsg(Object value) {
2705            return "Attempt to insert " + value.getClass() +
2706                " value into map with value type " + valueType;
2707        }
2708
2709        CheckedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) {
2710            if (m == null || keyType == null || valueType == null)
2711                throw new NullPointerException();
2712            this.m = m;
2713            this.keyType = keyType;
2714            this.valueType = valueType;
2715        }
2716
2717        public int size()                      { return m.size(); }
2718        public boolean isEmpty()               { return m.isEmpty(); }
2719        public boolean containsKey(Object key) { return m.containsKey(key); }
2720        public boolean containsValue(Object v) { return m.containsValue(v); }
2721        public V get(Object key)               { return m.get(key); }
2722        public V remove(Object key)            { return m.remove(key); }
2723        public void clear()                    { m.clear(); }
2724        public Set<K> keySet()                 { return m.keySet(); }
2725        public Collection<V> values()          { return m.values(); }
2726        public boolean equals(Object o)        { return o == this || m.equals(o); }
2727        public int hashCode()                  { return m.hashCode(); }
2728        public String toString()               { return m.toString(); }
2729
2730        public V put(K key, V value) {
2731            typeCheck(key, value);
2732            return m.put(key, value);
2733        }
2734
2735        @SuppressWarnings("unchecked")
2736        public void putAll(Map<? extends K, ? extends V> t) {
2737            // Satisfy the following goals:
2738            // - good diagnostics in case of type mismatch
2739            // - all-or-nothing semantics
2740            // - protection from malicious t
2741            // - correct behavior if t is a concurrent map
2742            Object[] entries = t.entrySet().toArray();
2743            List<Map.Entry<K,V>> checked = new ArrayList<>(entries.length);
2744            for (Object o : entries) {
2745                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
2746                Object k = e.getKey();
2747                Object v = e.getValue();
2748                typeCheck(k, v);
2749                checked.add(
2750                    new AbstractMap.SimpleImmutableEntry<>((K) k, (V) v));
2751            }
2752            for (Map.Entry<K,V> e : checked)
2753                m.put(e.getKey(), e.getValue());
2754        }
2755
2756        private transient Set<Map.Entry<K,V>> entrySet = null;
2757
2758        public Set<Map.Entry<K,V>> entrySet() {
2759            if (entrySet==null)
2760                entrySet = new CheckedEntrySet<>(m.entrySet(), valueType);
2761            return entrySet;
2762        }
2763
2764        // Override default methods in Map
2765        @Override
2766        public void forEach(BiConsumer<? super K, ? super V> action) {
2767            m.forEach(action);
2768        }
2769
2770        /**
2771         * We need this class in addition to CheckedSet as Map.Entry permits
2772         * modification of the backing Map via the setValue operation.  This
2773         * class is subtle: there are many possible attacks that must be
2774         * thwarted.
2775         *
2776         * @serial exclude
2777         */
2778        static class CheckedEntrySet<K,V> implements Set<Map.Entry<K,V>> {
2779            private final Set<Map.Entry<K,V>> s;
2780            private final Class<V> valueType;
2781
2782            CheckedEntrySet(Set<Map.Entry<K, V>> s, Class<V> valueType) {
2783                this.s = s;
2784                this.valueType = valueType;
2785            }
2786
2787            public int size()        { return s.size(); }
2788            public boolean isEmpty() { return s.isEmpty(); }
2789            public String toString() { return s.toString(); }
2790            public int hashCode()    { return s.hashCode(); }
2791            public void clear()      {        s.clear(); }
2792
2793            public boolean add(Map.Entry<K, V> e) {
2794                throw new UnsupportedOperationException();
2795            }
2796            public boolean addAll(Collection<? extends Map.Entry<K, V>> coll) {
2797                throw new UnsupportedOperationException();
2798            }
2799
2800            public Iterator<Map.Entry<K,V>> iterator() {
2801                final Iterator<Map.Entry<K, V>> i = s.iterator();
2802                final Class<V> valueType = this.valueType;
2803
2804                return new Iterator<Map.Entry<K,V>>() {
2805                    public boolean hasNext() { return i.hasNext(); }
2806                    public void remove()     { i.remove(); }
2807
2808                    public Map.Entry<K,V> next() {
2809                        return checkedEntry(i.next(), valueType);
2810                    }
2811                };
2812            }
2813
2814            @SuppressWarnings("unchecked")
2815            public Object[] toArray() {
2816                Object[] source = s.toArray();
2817
2818                /*
2819                 * Ensure that we don't get an ArrayStoreException even if
2820                 * s.toArray returns an array of something other than Object
2821                 */
2822                Object[] dest = (CheckedEntry.class.isInstance(
2823                    source.getClass().getComponentType()) ? source :
2824                                 new Object[source.length]);
2825
2826                for (int i = 0; i < source.length; i++)
2827                    dest[i] = checkedEntry((Map.Entry<K,V>)source[i],
2828                                           valueType);
2829                return dest;
2830            }
2831
2832            @SuppressWarnings("unchecked")
2833            public <T> T[] toArray(T[] a) {
2834                // We don't pass a to s.toArray, to avoid window of
2835                // vulnerability wherein an unscrupulous multithreaded client
2836                // could get his hands on raw (unwrapped) Entries from s.
2837                T[] arr = s.toArray(a.length==0 ? a : Arrays.copyOf(a, 0));
2838
2839                for (int i=0; i<arr.length; i++)
2840                    arr[i] = (T) checkedEntry((Map.Entry<K,V>)arr[i],
2841                                              valueType);
2842                if (arr.length > a.length)
2843                    return arr;
2844
2845                System.arraycopy(arr, 0, a, 0, arr.length);
2846                if (a.length > arr.length)
2847                    a[arr.length] = null;
2848                return a;
2849            }
2850
2851            /**
2852             * This method is overridden to protect the backing set against
2853             * an object with a nefarious equals function that senses
2854             * that the equality-candidate is Map.Entry and calls its
2855             * setValue method.
2856             */
2857            public boolean contains(Object o) {
2858                if (!(o instanceof Map.Entry))
2859                    return false;
2860                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
2861                return s.contains(
2862                    (e instanceof CheckedEntry) ? e : checkedEntry(e, valueType));
2863            }
2864
2865            /**
2866             * The bulk collection methods are overridden to protect
2867             * against an unscrupulous collection whose contains(Object o)
2868             * method senses when o is a Map.Entry, and calls o.setValue.
2869             */
2870            public boolean containsAll(Collection<?> c) {
2871                for (Object o : c)
2872                    if (!contains(o)) // Invokes safe contains() above
2873                        return false;
2874                return true;
2875            }
2876
2877            public boolean remove(Object o) {
2878                if (!(o instanceof Map.Entry))
2879                    return false;
2880                return s.remove(new AbstractMap.SimpleImmutableEntry
2881                                <>((Map.Entry<?,?>)o));
2882            }
2883
2884            public boolean removeAll(Collection<?> c) {
2885                return batchRemove(c, false);
2886            }
2887            public boolean retainAll(Collection<?> c) {
2888                return batchRemove(c, true);
2889            }
2890            private boolean batchRemove(Collection<?> c, boolean complement) {
2891                boolean modified = false;
2892                Iterator<Map.Entry<K,V>> it = iterator();
2893                while (it.hasNext()) {
2894                    if (c.contains(it.next()) != complement) {
2895                        it.remove();
2896                        modified = true;
2897                    }
2898                }
2899                return modified;
2900            }
2901
2902            public boolean equals(Object o) {
2903                if (o == this)
2904                    return true;
2905                if (!(o instanceof Set))
2906                    return false;
2907                Set<?> that = (Set<?>) o;
2908                return that.size() == s.size()
2909                    && containsAll(that); // Invokes safe containsAll() above
2910            }
2911
2912            static <K,V,T> CheckedEntry<K,V,T> checkedEntry(Map.Entry<K,V> e,
2913                                                            Class<T> valueType) {
2914                return new CheckedEntry<>(e, valueType);
2915            }
2916
2917            /**
2918             * This "wrapper class" serves two purposes: it prevents
2919             * the client from modifying the backing Map, by short-circuiting
2920             * the setValue method, and it protects the backing Map against
2921             * an ill-behaved Map.Entry that attempts to modify another
2922             * Map.Entry when asked to perform an equality check.
2923             */
2924            private static class CheckedEntry<K,V,T> implements Map.Entry<K,V> {
2925                private final Map.Entry<K, V> e;
2926                private final Class<T> valueType;
2927
2928                CheckedEntry(Map.Entry<K, V> e, Class<T> valueType) {
2929                    this.e = e;
2930                    this.valueType = valueType;
2931                }
2932
2933                public K getKey()        { return e.getKey(); }
2934                public V getValue()      { return e.getValue(); }
2935                public int hashCode()    { return e.hashCode(); }
2936                public String toString() { return e.toString(); }
2937
2938                public V setValue(V value) {
2939                    if (value != null && !valueType.isInstance(value))
2940                        throw new ClassCastException(badValueMsg(value));
2941                    return e.setValue(value);
2942                }
2943
2944                private String badValueMsg(Object value) {
2945                    return "Attempt to insert " + value.getClass() +
2946                        " value into map with value type " + valueType;
2947                }
2948
2949                public boolean equals(Object o) {
2950                    if (o == this)
2951                        return true;
2952                    if (!(o instanceof Map.Entry))
2953                        return false;
2954                    return e.equals(new AbstractMap.SimpleImmutableEntry
2955                                    <>((Map.Entry<?,?>)o));
2956                }
2957            }
2958        }
2959    }
2960
2961    /**
2962     * Returns a dynamically typesafe view of the specified sorted map.
2963     * Any attempt to insert a mapping whose key or value have the wrong
2964     * type will result in an immediate {@link ClassCastException}.
2965     * Similarly, any attempt to modify the value currently associated with
2966     * a key will result in an immediate {@link ClassCastException},
2967     * whether the modification is attempted directly through the map
2968     * itself, or through a {@link Map.Entry} instance obtained from the
2969     * map's {@link Map#entrySet() entry set} view.
2970     *
2971     * <p>Assuming a map contains no incorrectly typed keys or values
2972     * prior to the time a dynamically typesafe view is generated, and
2973     * that all subsequent access to the map takes place through the view
2974     * (or one of its collection views), it is <i>guaranteed</i> that the
2975     * map cannot contain an incorrectly typed key or value.
2976     *
2977     * <p>A discussion of the use of dynamically typesafe views may be
2978     * found in the documentation for the {@link #checkedCollection
2979     * checkedCollection} method.
2980     *
2981     * <p>The returned map will be serializable if the specified map is
2982     * serializable.
2983     *
2984     * <p>Since {@code null} is considered to be a value of any reference
2985     * type, the returned map permits insertion of null keys or values
2986     * whenever the backing map does.
2987     *
2988     * @param m the map for which a dynamically typesafe view is to be
2989     *          returned
2990     * @param keyType the type of key that {@code m} is permitted to hold
2991     * @param valueType the type of value that {@code m} is permitted to hold
2992     * @return a dynamically typesafe view of the specified map
2993     * @since 1.5
2994     */
2995    public static <K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K, V> m,
2996                                                        Class<K> keyType,
2997                                                        Class<V> valueType) {
2998        return new CheckedSortedMap<>(m, keyType, valueType);
2999    }
3000
3001    /**
3002     * @serial include
3003     */
3004    static class CheckedSortedMap<K,V> extends CheckedMap<K,V>
3005        implements SortedMap<K,V>, Serializable
3006    {
3007        private static final long serialVersionUID = 1599671320688067438L;
3008
3009        private final SortedMap<K, V> sm;
3010
3011        CheckedSortedMap(SortedMap<K, V> m,
3012                         Class<K> keyType, Class<V> valueType) {
3013            super(m, keyType, valueType);
3014            sm = m;
3015        }
3016
3017        public Comparator<? super K> comparator() { return sm.comparator(); }
3018        public K firstKey()                       { return sm.firstKey(); }
3019        public K lastKey()                        { return sm.lastKey(); }
3020
3021        public SortedMap<K,V> subMap(K fromKey, K toKey) {
3022            return checkedSortedMap(sm.subMap(fromKey, toKey),
3023                                    keyType, valueType);
3024        }
3025        public SortedMap<K,V> headMap(K toKey) {
3026            return checkedSortedMap(sm.headMap(toKey), keyType, valueType);
3027        }
3028        public SortedMap<K,V> tailMap(K fromKey) {
3029            return checkedSortedMap(sm.tailMap(fromKey), keyType, valueType);
3030        }
3031    }
3032
3033    // Empty collections
3034
3035    /**
3036     * Returns an iterator that has no elements.  More precisely,
3037     *
3038     * <ul compact>
3039     *
3040     * <li>{@link Iterator#hasNext hasNext} always returns {@code
3041     * false}.
3042     *
3043     * <li>{@link Iterator#next next} always throws {@link
3044     * NoSuchElementException}.
3045     *
3046     * <li>{@link Iterator#remove remove} always throws {@link
3047     * IllegalStateException}.
3048     *
3049     * </ul>
3050     *
3051     * <p>Implementations of this method are permitted, but not
3052     * required, to return the same object from multiple invocations.
3053     *
3054     * @return an empty iterator
3055     * @since 1.7
3056     */
3057    @SuppressWarnings("unchecked")
3058    public static <T> Iterator<T> emptyIterator() {
3059        return (Iterator<T>) EmptyIterator.EMPTY_ITERATOR;
3060    }
3061
3062    private static class EmptyIterator<E> implements Iterator<E> {
3063        static final EmptyIterator<Object> EMPTY_ITERATOR
3064            = new EmptyIterator<>();
3065
3066        public boolean hasNext() { return false; }
3067        public E next() { throw new NoSuchElementException(); }
3068        public void remove() { throw new IllegalStateException(); }
3069    }
3070
3071    /**
3072     * Returns a list iterator that has no elements.  More precisely,
3073     *
3074     * <ul compact>
3075     *
3076     * <li>{@link Iterator#hasNext hasNext} and {@link
3077     * ListIterator#hasPrevious hasPrevious} always return {@code
3078     * false}.
3079     *
3080     * <li>{@link Iterator#next next} and {@link ListIterator#previous
3081     * previous} always throw {@link NoSuchElementException}.
3082     *
3083     * <li>{@link Iterator#remove remove} and {@link ListIterator#set
3084     * set} always throw {@link IllegalStateException}.
3085     *
3086     * <li>{@link ListIterator#add add} always throws {@link
3087     * UnsupportedOperationException}.
3088     *
3089     * <li>{@link ListIterator#nextIndex nextIndex} always returns
3090     * {@code 0} .
3091     *
3092     * <li>{@link ListIterator#previousIndex previousIndex} always
3093     * returns {@code -1}.
3094     *
3095     * </ul>
3096     *
3097     * <p>Implementations of this method are permitted, but not
3098     * required, to return the same object from multiple invocations.
3099     *
3100     * @return an empty list iterator
3101     * @since 1.7
3102     */
3103    @SuppressWarnings("unchecked")
3104    public static <T> ListIterator<T> emptyListIterator() {
3105        return (ListIterator<T>) EmptyListIterator.EMPTY_ITERATOR;
3106    }
3107
3108    private static class EmptyListIterator<E>
3109        extends EmptyIterator<E>
3110        implements ListIterator<E>
3111    {
3112        static final EmptyListIterator<Object> EMPTY_ITERATOR
3113            = new EmptyListIterator<>();
3114
3115        public boolean hasPrevious() { return false; }
3116        public E previous() { throw new NoSuchElementException(); }
3117        public int nextIndex()     { return 0; }
3118        public int previousIndex() { return -1; }
3119        public void set(E e) { throw new IllegalStateException(); }
3120        public void add(E e) { throw new UnsupportedOperationException(); }
3121    }
3122
3123    /**
3124     * Returns an enumeration that has no elements.  More precisely,
3125     *
3126     * <ul compact>
3127     *
3128     * <li>{@link Enumeration#hasMoreElements hasMoreElements} always
3129     * returns {@code false}.
3130     *
3131     * <li> {@link Enumeration#nextElement nextElement} always throws
3132     * {@link NoSuchElementException}.
3133     *
3134     * </ul>
3135     *
3136     * <p>Implementations of this method are permitted, but not
3137     * required, to return the same object from multiple invocations.
3138     *
3139     * @return an empty enumeration
3140     * @since 1.7
3141     */
3142    @SuppressWarnings("unchecked")
3143    public static <T> Enumeration<T> emptyEnumeration() {
3144        return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
3145    }
3146
3147    private static class EmptyEnumeration<E> implements Enumeration<E> {
3148        static final EmptyEnumeration<Object> EMPTY_ENUMERATION
3149            = new EmptyEnumeration<>();
3150
3151        public boolean hasMoreElements() { return false; }
3152        public E nextElement() { throw new NoSuchElementException(); }
3153    }
3154
3155    /**
3156     * The empty set (immutable).  This set is serializable.
3157     *
3158     * @see #emptySet()
3159     */
3160    @SuppressWarnings("unchecked")
3161    public static final Set EMPTY_SET = new EmptySet<>();
3162
3163    /**
3164     * Returns the empty set (immutable).  This set is serializable.
3165     * Unlike the like-named field, this method is parameterized.
3166     *
3167     * <p>This example illustrates the type-safe way to obtain an empty set:
3168     * <pre>
3169     *     Set&lt;String&gt; s = Collections.emptySet();
3170     * </pre>
3171     * Implementation note:  Implementations of this method need not
3172     * create a separate <tt>Set</tt> object for each call.   Using this
3173     * method is likely to have comparable cost to using the like-named
3174     * field.  (Unlike this method, the field does not provide type safety.)
3175     *
3176     * @see #EMPTY_SET
3177     * @since 1.5
3178     */
3179    @SuppressWarnings("unchecked")
3180    public static final <T> Set<T> emptySet() {
3181        return (Set<T>) EMPTY_SET;
3182    }
3183
3184    /**
3185     * @serial include
3186     */
3187    private static class EmptySet<E>
3188        extends AbstractSet<E>
3189        implements Serializable
3190    {
3191        private static final long serialVersionUID = 1582296315990362920L;
3192
3193        public Iterator<E> iterator() { return emptyIterator(); }
3194
3195        public int size() {return 0;}
3196        public boolean isEmpty() {return true;}
3197
3198        public boolean contains(Object obj) {return false;}
3199        public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
3200
3201        public Object[] toArray() { return new Object[0]; }
3202
3203        public <T> T[] toArray(T[] a) {
3204            if (a.length > 0)
3205                a[0] = null;
3206            return a;
3207        }
3208
3209        // Preserves singleton property
3210        private Object readResolve() {
3211            return EMPTY_SET;
3212        }
3213
3214        // Override default methods in Collection
3215        @Override
3216        public void forEach(Consumer<? super E> action) {
3217            Objects.requireNonNull(action);
3218        }
3219    }
3220
3221    /**
3222     * The empty list (immutable).  This list is serializable.
3223     *
3224     * @see #emptyList()
3225     */
3226    @SuppressWarnings("unchecked")
3227    public static final List EMPTY_LIST = new EmptyList<>();
3228
3229    /**
3230     * Returns the empty list (immutable).  This list is serializable.
3231     *
3232     * <p>This example illustrates the type-safe way to obtain an empty list:
3233     * <pre>
3234     *     List&lt;String&gt; s = Collections.emptyList();
3235     * </pre>
3236     * Implementation note:  Implementations of this method need not
3237     * create a separate <tt>List</tt> object for each call.   Using this
3238     * method is likely to have comparable cost to using the like-named
3239     * field.  (Unlike this method, the field does not provide type safety.)
3240     *
3241     * @see #EMPTY_LIST
3242     * @since 1.5
3243     */
3244    @SuppressWarnings("unchecked")
3245    public static final <T> List<T> emptyList() {
3246        return (List<T>) EMPTY_LIST;
3247    }
3248
3249    /**
3250     * @serial include
3251     */
3252    private static class EmptyList<E>
3253        extends AbstractList<E>
3254        implements RandomAccess, Serializable {
3255        private static final long serialVersionUID = 8842843931221139166L;
3256
3257        public Iterator<E> iterator() {
3258            return emptyIterator();
3259        }
3260        public ListIterator<E> listIterator() {
3261            return emptyListIterator();
3262        }
3263
3264        public int size() {return 0;}
3265        public boolean isEmpty() {return true;}
3266
3267        public boolean contains(Object obj) {return false;}
3268        public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
3269
3270        public Object[] toArray() { return new Object[0]; }
3271
3272        public <T> T[] toArray(T[] a) {
3273            if (a.length > 0)
3274                a[0] = null;
3275            return a;
3276        }
3277
3278        public E get(int index) {
3279            throw new IndexOutOfBoundsException("Index: "+index);
3280        }
3281
3282        public boolean equals(Object o) {
3283            return (o instanceof List) && ((List<?>)o).isEmpty();
3284        }
3285
3286        public int hashCode() { return 1; }
3287
3288        // Preserves singleton property
3289        private Object readResolve() {
3290            return EMPTY_LIST;
3291        }
3292
3293        // Override default methods in Collection
3294        @Override
3295        public void forEach(Consumer<? super E> action) {
3296            Objects.requireNonNull(action);
3297        }
3298    }
3299
3300    /**
3301     * The empty map (immutable).  This map is serializable.
3302     *
3303     * @see #emptyMap()
3304     * @since 1.3
3305     */
3306    @SuppressWarnings("unchecked")
3307    public static final Map EMPTY_MAP = new EmptyMap<>();
3308
3309    /**
3310     * Returns the empty map (immutable).  This map is serializable.
3311     *
3312     * <p>This example illustrates the type-safe way to obtain an empty set:
3313     * <pre>
3314     *     Map&lt;String, Date&gt; s = Collections.emptyMap();
3315     * </pre>
3316     * Implementation note:  Implementations of this method need not
3317     * create a separate <tt>Map</tt> object for each call.   Using this
3318     * method is likely to have comparable cost to using the like-named
3319     * field.  (Unlike this method, the field does not provide type safety.)
3320     *
3321     * @see #EMPTY_MAP
3322     * @since 1.5
3323     */
3324    @SuppressWarnings("unchecked")
3325    public static final <K,V> Map<K,V> emptyMap() {
3326        return (Map<K,V>) EMPTY_MAP;
3327    }
3328
3329    /**
3330     * @serial include
3331     */
3332    private static class EmptyMap<K,V>
3333        extends AbstractMap<K,V>
3334        implements Serializable
3335    {
3336        private static final long serialVersionUID = 6428348081105594320L;
3337
3338        public int size()                          {return 0;}
3339        public boolean isEmpty()                   {return true;}
3340        public boolean containsKey(Object key)     {return false;}
3341        public boolean containsValue(Object value) {return false;}
3342        public V get(Object key)                   {return null;}
3343        public Set<K> keySet()                     {return emptySet();}
3344        public Collection<V> values()              {return emptySet();}
3345        public Set<Map.Entry<K,V>> entrySet()      {return emptySet();}
3346
3347        public boolean equals(Object o) {
3348            return (o instanceof Map) && ((Map<?,?>)o).isEmpty();
3349        }
3350
3351        public int hashCode()                      {return 0;}
3352
3353        // Preserves singleton property
3354        private Object readResolve() {
3355            return EMPTY_MAP;
3356        }
3357
3358        // Override default methods in Map
3359        @Override
3360        public void forEach(BiConsumer<? super K, ? super V> action) {
3361            Objects.requireNonNull(action);
3362        }
3363    }
3364
3365    // Singleton collections
3366
3367    /**
3368     * Returns an immutable set containing only the specified object.
3369     * The returned set is serializable.
3370     *
3371     * @param o the sole object to be stored in the returned set.
3372     * @return an immutable set containing only the specified object.
3373     */
3374    public static <E> Set<E> singleton(E o) {
3375        return new SingletonSet<>(o);
3376    }
3377
3378    static <E> Iterator<E> singletonIterator(final E e) {
3379        return new Iterator<E>() {
3380            private boolean hasNext = true;
3381            public boolean hasNext() {
3382                return hasNext;
3383            }
3384            public E next() {
3385                if (hasNext) {
3386                    hasNext = false;
3387                    return e;
3388                }
3389                throw new NoSuchElementException();
3390            }
3391            public void remove() {
3392                throw new UnsupportedOperationException();
3393            }
3394        };
3395    }
3396
3397    /**
3398     * @serial include
3399     */
3400    private static class SingletonSet<E>
3401        extends AbstractSet<E>
3402        implements Serializable
3403    {
3404        private static final long serialVersionUID = 3193687207550431679L;
3405
3406        private final E element;
3407
3408        SingletonSet(E e) {element = e;}
3409
3410        public Iterator<E> iterator() {
3411            return singletonIterator(element);
3412        }
3413
3414        public int size() {return 1;}
3415
3416        public boolean contains(Object o) {return eq(o, element);}
3417
3418        // Override default methods for Collection
3419        @Override
3420        public void forEach(Consumer<? super E> action) {
3421            action.accept(element);
3422        }
3423    }
3424
3425    /**
3426     * Returns an immutable list containing only the specified object.
3427     * The returned list is serializable.
3428     *
3429     * @param o the sole object to be stored in the returned list.
3430     * @return an immutable list containing only the specified object.
3431     * @since 1.3
3432     */
3433    public static <E> List<E> singletonList(E o) {
3434        return new SingletonList<>(o);
3435    }
3436
3437    /**
3438     * @serial include
3439     */
3440    private static class SingletonList<E>
3441        extends AbstractList<E>
3442        implements RandomAccess, Serializable {
3443
3444        private static final long serialVersionUID = 3093736618740652951L;
3445
3446        private final E element;
3447
3448        SingletonList(E obj)                {element = obj;}
3449
3450        public Iterator<E> iterator() {
3451            return singletonIterator(element);
3452        }
3453
3454        public int size()                   {return 1;}
3455
3456        public boolean contains(Object obj) {return eq(obj, element);}
3457
3458        public E get(int index) {
3459            if (index != 0)
3460              throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
3461            return element;
3462        }
3463
3464        // Override default methods for Collection
3465        @Override
3466        public void forEach(Consumer<? super E> action) {
3467            action.accept(element);
3468        }
3469    }
3470
3471    /**
3472     * Returns an immutable map, mapping only the specified key to the
3473     * specified value.  The returned map is serializable.
3474     *
3475     * @param key the sole key to be stored in the returned map.
3476     * @param value the value to which the returned map maps <tt>key</tt>.
3477     * @return an immutable map containing only the specified key-value
3478     *         mapping.
3479     * @since 1.3
3480     */
3481    public static <K,V> Map<K,V> singletonMap(K key, V value) {
3482        return new SingletonMap<>(key, value);
3483    }
3484
3485    /**
3486     * @serial include
3487     */
3488    private static class SingletonMap<K,V>
3489          extends AbstractMap<K,V>
3490          implements Serializable {
3491        private static final long serialVersionUID = -6979724477215052911L;
3492
3493        private final K k;
3494        private final V v;
3495
3496        SingletonMap(K key, V value) {
3497            k = key;
3498            v = value;
3499        }
3500
3501        public int size()                          {return 1;}
3502
3503        public boolean isEmpty()                   {return false;}
3504
3505        public boolean containsKey(Object key)     {return eq(key, k);}
3506
3507        public boolean containsValue(Object value) {return eq(value, v);}
3508
3509        public V get(Object key)                   {return (eq(key, k) ? v : null);}
3510
3511        private transient Set<K> keySet = null;
3512        private transient Set<Map.Entry<K,V>> entrySet = null;
3513        private transient Collection<V> values = null;
3514
3515        public Set<K> keySet() {
3516            if (keySet==null)
3517                keySet = singleton(k);
3518            return keySet;
3519        }
3520
3521        public Set<Map.Entry<K,V>> entrySet() {
3522            if (entrySet==null)
3523                entrySet = Collections.<Map.Entry<K,V>>singleton(
3524                    new SimpleImmutableEntry<>(k, v));
3525            return entrySet;
3526        }
3527
3528        public Collection<V> values() {
3529            if (values==null)
3530                values = singleton(v);
3531            return values;
3532        }
3533
3534        // Override default methods in Map
3535        @Override
3536        public void forEach(BiConsumer<? super K, ? super V> action) {
3537            action.accept(k, v);
3538        }
3539
3540    }
3541
3542    // Miscellaneous
3543
3544    /**
3545     * Returns an immutable list consisting of <tt>n</tt> copies of the
3546     * specified object.  The newly allocated data object is tiny (it contains
3547     * a single reference to the data object).  This method is useful in
3548     * combination with the <tt>List.addAll</tt> method to grow lists.
3549     * The returned list is serializable.
3550     *
3551     * @param  n the number of elements in the returned list.
3552     * @param  o the element to appear repeatedly in the returned list.
3553     * @return an immutable list consisting of <tt>n</tt> copies of the
3554     *         specified object.
3555     * @throws IllegalArgumentException if {@code n < 0}
3556     * @see    List#addAll(Collection)
3557     * @see    List#addAll(int, Collection)
3558     */
3559    public static <T> List<T> nCopies(int n, T o) {
3560        if (n < 0)
3561            throw new IllegalArgumentException("List length = " + n);
3562        return new CopiesList<>(n, o);
3563    }
3564
3565    /**
3566     * @serial include
3567     */
3568    private static class CopiesList<E>
3569        extends AbstractList<E>
3570        implements RandomAccess, Serializable
3571    {
3572        private static final long serialVersionUID = 2739099268398711800L;
3573
3574        final int n;
3575        final E element;
3576
3577        CopiesList(int n, E e) {
3578            assert n >= 0;
3579            this.n = n;
3580            element = e;
3581        }
3582
3583        public int size() {
3584            return n;
3585        }
3586
3587        public boolean contains(Object obj) {
3588            return n != 0 && eq(obj, element);
3589        }
3590
3591        public int indexOf(Object o) {
3592            return contains(o) ? 0 : -1;
3593        }
3594
3595        public int lastIndexOf(Object o) {
3596            return contains(o) ? n - 1 : -1;
3597        }
3598
3599        public E get(int index) {
3600            if (index < 0 || index >= n)
3601                throw new IndexOutOfBoundsException("Index: "+index+
3602                                                    ", Size: "+n);
3603            return element;
3604        }
3605
3606        public Object[] toArray() {
3607            final Object[] a = new Object[n];
3608            if (element != null)
3609                Arrays.fill(a, 0, n, element);
3610            return a;
3611        }
3612
3613        public <T> T[] toArray(T[] a) {
3614            final int n = this.n;
3615            if (a.length < n) {
3616                a = (T[])java.lang.reflect.Array
3617                    .newInstance(a.getClass().getComponentType(), n);
3618                if (element != null)
3619                    Arrays.fill(a, 0, n, element);
3620            } else {
3621                Arrays.fill(a, 0, n, element);
3622                if (a.length > n)
3623                    a[n] = null;
3624            }
3625            return a;
3626        }
3627
3628        public List<E> subList(int fromIndex, int toIndex) {
3629            if (fromIndex < 0)
3630                throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
3631            if (toIndex > n)
3632                throw new IndexOutOfBoundsException("toIndex = " + toIndex);
3633            if (fromIndex > toIndex)
3634                throw new IllegalArgumentException("fromIndex(" + fromIndex +
3635                                                   ") > toIndex(" + toIndex + ")");
3636            return new CopiesList<>(toIndex - fromIndex, element);
3637        }
3638    }
3639
3640    /**
3641     * Returns a comparator that imposes the reverse of the <em>natural
3642     * ordering</em> on a collection of objects that implement the
3643     * {@code Comparable} interface.  (The natural ordering is the ordering
3644     * imposed by the objects' own {@code compareTo} method.)  This enables a
3645     * simple idiom for sorting (or maintaining) collections (or arrays) of
3646     * objects that implement the {@code Comparable} interface in
3647     * reverse-natural-order.  For example, suppose {@code a} is an array of
3648     * strings. Then: <pre>
3649     *          Arrays.sort(a, Collections.reverseOrder());
3650     * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p>
3651     *
3652     * The returned comparator is serializable.
3653     *
3654     * @return A comparator that imposes the reverse of the <i>natural
3655     *         ordering</i> on a collection of objects that implement
3656     *         the <tt>Comparable</tt> interface.
3657     * @see Comparable
3658     */
3659    public static <T> Comparator<T> reverseOrder() {
3660        return (Comparator<T>) ReverseComparator.REVERSE_ORDER;
3661    }
3662
3663    /**
3664     * @serial include
3665     */
3666    private static class ReverseComparator
3667        implements Comparator<Comparable<Object>>, Serializable {
3668
3669        private static final long serialVersionUID = 7207038068494060240L;
3670
3671        static final ReverseComparator REVERSE_ORDER
3672            = new ReverseComparator();
3673
3674        public int compare(Comparable<Object> c1, Comparable<Object> c2) {
3675            return c2.compareTo(c1);
3676        }
3677
3678        private Object readResolve() { return reverseOrder(); }
3679    }
3680
3681    /**
3682     * Returns a comparator that imposes the reverse ordering of the specified
3683     * comparator.  If the specified comparator is {@code null}, this method is
3684     * equivalent to {@link #reverseOrder()} (in other words, it returns a
3685     * comparator that imposes the reverse of the <em>natural ordering</em> on
3686     * a collection of objects that implement the Comparable interface).
3687     *
3688     * <p>The returned comparator is serializable (assuming the specified
3689     * comparator is also serializable or {@code null}).
3690     *
3691     * @param cmp a comparator who's ordering is to be reversed by the returned
3692     * comparator or {@code null}
3693     * @return A comparator that imposes the reverse ordering of the
3694     *         specified comparator.
3695     * @since 1.5
3696     */
3697    public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) {
3698        if (cmp == null)
3699            return reverseOrder();
3700
3701        if (cmp instanceof ReverseComparator2)
3702            return ((ReverseComparator2<T>)cmp).cmp;
3703
3704        return new ReverseComparator2<>(cmp);
3705    }
3706
3707    /**
3708     * @serial include
3709     */
3710    private static class ReverseComparator2<T> implements Comparator<T>,
3711        Serializable
3712    {
3713        private static final long serialVersionUID = 4374092139857L;
3714
3715        /**
3716         * The comparator specified in the static factory.  This will never
3717         * be null, as the static factory returns a ReverseComparator
3718         * instance if its argument is null.
3719         *
3720         * @serial
3721         */
3722        final Comparator<T> cmp;
3723
3724        ReverseComparator2(Comparator<T> cmp) {
3725            assert cmp != null;
3726            this.cmp = cmp;
3727        }
3728
3729        public int compare(T t1, T t2) {
3730            return cmp.compare(t2, t1);
3731        }
3732
3733        public boolean equals(Object o) {
3734            return (o == this) ||
3735                (o instanceof ReverseComparator2 &&
3736                 cmp.equals(((ReverseComparator2)o).cmp));
3737        }
3738
3739        public int hashCode() {
3740            return cmp.hashCode() ^ Integer.MIN_VALUE;
3741        }
3742    }
3743
3744    /**
3745     * Returns an enumeration over the specified collection.  This provides
3746     * interoperability with legacy APIs that require an enumeration
3747     * as input.
3748     *
3749     * @param c the collection for which an enumeration is to be returned.
3750     * @return an enumeration over the specified collection.
3751     * @see Enumeration
3752     */
3753    public static <T> Enumeration<T> enumeration(final Collection<T> c) {
3754        return new Enumeration<T>() {
3755            private final Iterator<T> i = c.iterator();
3756
3757            public boolean hasMoreElements() {
3758                return i.hasNext();
3759            }
3760
3761            public T nextElement() {
3762                return i.next();
3763            }
3764        };
3765    }
3766
3767    /**
3768     * Returns an array list containing the elements returned by the
3769     * specified enumeration in the order they are returned by the
3770     * enumeration.  This method provides interoperability between
3771     * legacy APIs that return enumerations and new APIs that require
3772     * collections.
3773     *
3774     * @param e enumeration providing elements for the returned
3775     *          array list
3776     * @return an array list containing the elements returned
3777     *         by the specified enumeration.
3778     * @since 1.4
3779     * @see Enumeration
3780     * @see ArrayList
3781     */
3782    public static <T> ArrayList<T> list(Enumeration<T> e) {
3783        ArrayList<T> l = new ArrayList<>();
3784        while (e.hasMoreElements())
3785            l.add(e.nextElement());
3786        return l;
3787    }
3788
3789    /**
3790     * Returns true if the specified arguments are equal, or both null.
3791     */
3792    static boolean eq(Object o1, Object o2) {
3793        return o1==null ? o2==null : o1.equals(o2);
3794    }
3795
3796    /**
3797     * Returns the number of elements in the specified collection equal to the
3798     * specified object.  More formally, returns the number of elements
3799     * <tt>e</tt> in the collection such that
3800     * <tt>(o == null ? e == null : o.equals(e))</tt>.
3801     *
3802     * @param c the collection in which to determine the frequency
3803     *     of <tt>o</tt>
3804     * @param o the object whose frequency is to be determined
3805     * @throws NullPointerException if <tt>c</tt> is null
3806     * @since 1.5
3807     */
3808    public static int frequency(Collection<?> c, Object o) {
3809        int result = 0;
3810        if (o == null) {
3811            for (Object e : c)
3812                if (e == null)
3813                    result++;
3814        } else {
3815            for (Object e : c)
3816                if (o.equals(e))
3817                    result++;
3818        }
3819        return result;
3820    }
3821
3822    /**
3823     * Returns {@code true} if the two specified collections have no
3824     * elements in common.
3825     *
3826     * <p>Care must be exercised if this method is used on collections that
3827     * do not comply with the general contract for {@code Collection}.
3828     * Implementations may elect to iterate over either collection and test
3829     * for containment in the other collection (or to perform any equivalent
3830     * computation).  If either collection uses a nonstandard equality test
3831     * (as does a {@link SortedSet} whose ordering is not <em>compatible with
3832     * equals</em>, or the key set of an {@link IdentityHashMap}), both
3833     * collections must use the same nonstandard equality test, or the
3834     * result of this method is undefined.
3835     *
3836     * <p>Care must also be exercised when using collections that have
3837     * restrictions on the elements that they may contain. Collection
3838     * implementations are allowed to throw exceptions for any operation
3839     * involving elements they deem ineligible. For absolute safety the
3840     * specified collections should contain only elements which are
3841     * eligible elements for both collections.
3842     *
3843     * <p>Note that it is permissible to pass the same collection in both
3844     * parameters, in which case the method will return {@code true} if and
3845     * only if the collection is empty.
3846     *
3847     * @param c1 a collection
3848     * @param c2 a collection
3849     * @return {@code true} if the two specified collections have no
3850     * elements in common.
3851     * @throws NullPointerException if either collection is {@code null}.
3852     * @throws NullPointerException if one collection contains a {@code null}
3853     * element and {@code null} is not an eligible element for the other collection.
3854     * (<a href="Collection.html#optional-restrictions">optional</a>)
3855     * @throws ClassCastException if one collection contains an element that is
3856     * of a type which is ineligible for the other collection.
3857     * (<a href="Collection.html#optional-restrictions">optional</a>)
3858     * @since 1.5
3859     */
3860    public static boolean disjoint(Collection<?> c1, Collection<?> c2) {
3861        // The collection to be used for contains(). Preference is given to
3862        // the collection who's contains() has lower O() complexity.
3863        Collection<?> contains = c2;
3864        // The collection to be iterated. If the collections' contains() impl
3865        // are of different O() complexity, the collection with slower
3866        // contains() will be used for iteration. For collections who's
3867        // contains() are of the same complexity then best performance is
3868        // achieved by iterating the smaller collection.
3869        Collection<?> iterate = c1;
3870
3871        // Performance optimization cases. The heuristics:
3872        //   1. Generally iterate over c1.
3873        //   2. If c1 is a Set then iterate over c2.
3874        //   3. If either collection is empty then result is always true.
3875        //   4. Iterate over the smaller Collection.
3876        if (c1 instanceof Set) {
3877            // Use c1 for contains as a Set's contains() is expected to perform
3878            // better than O(N/2)
3879            iterate = c2;
3880            contains = c1;
3881        } else if (!(c2 instanceof Set)) {
3882            // Both are mere Collections. Iterate over smaller collection.
3883            // Example: If c1 contains 3 elements and c2 contains 50 elements and
3884            // assuming contains() requires ceiling(N/2) comparisons then
3885            // checking for all c1 elements in c2 would require 75 comparisons
3886            // (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring
3887            // 100 comparisons (50 * ceiling(3/2)).
3888            int c1size = c1.size();
3889            int c2size = c2.size();
3890            if (c1size == 0 || c2size == 0) {
3891                // At least one collection is empty. Nothing will match.
3892                return true;
3893            }
3894
3895            if (c1size > c2size) {
3896                iterate = c2;
3897                contains = c1;
3898            }
3899        }
3900
3901        for (Object e : iterate) {
3902            if (contains.contains(e)) {
3903               // Found a common element. Collections are not disjoint.
3904                return false;
3905            }
3906        }
3907
3908        // No common elements were found.
3909        return true;
3910    }
3911
3912    /**
3913     * Adds all of the specified elements to the specified collection.
3914     * Elements to be added may be specified individually or as an array.
3915     * The behavior of this convenience method is identical to that of
3916     * <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely
3917     * to run significantly faster under most implementations.
3918     *
3919     * <p>When elements are specified individually, this method provides a
3920     * convenient way to add a few elements to an existing collection:
3921     * <pre>
3922     *     Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
3923     * </pre>
3924     *
3925     * @param c the collection into which <tt>elements</tt> are to be inserted
3926     * @param elements the elements to insert into <tt>c</tt>
3927     * @return <tt>true</tt> if the collection changed as a result of the call
3928     * @throws UnsupportedOperationException if <tt>c</tt> does not support
3929     *         the <tt>add</tt> operation
3930     * @throws NullPointerException if <tt>elements</tt> contains one or more
3931     *         null values and <tt>c</tt> does not permit null elements, or
3932     *         if <tt>c</tt> or <tt>elements</tt> are <tt>null</tt>
3933     * @throws IllegalArgumentException if some property of a value in
3934     *         <tt>elements</tt> prevents it from being added to <tt>c</tt>
3935     * @see Collection#addAll(Collection)
3936     * @since 1.5
3937     */
3938    @SafeVarargs
3939    public static <T> boolean addAll(Collection<? super T> c, T... elements) {
3940        boolean result = false;
3941        for (T element : elements)
3942            result |= c.add(element);
3943        return result;
3944    }
3945
3946    /**
3947     * Returns a set backed by the specified map.  The resulting set displays
3948     * the same ordering, concurrency, and performance characteristics as the
3949     * backing map.  In essence, this factory method provides a {@link Set}
3950     * implementation corresponding to any {@link Map} implementation.  There
3951     * is no need to use this method on a {@link Map} implementation that
3952     * already has a corresponding {@link Set} implementation (such as {@link
3953     * HashMap} or {@link TreeMap}).
3954     *
3955     * <p>Each method invocation on the set returned by this method results in
3956     * exactly one method invocation on the backing map or its <tt>keySet</tt>
3957     * view, with one exception.  The <tt>addAll</tt> method is implemented
3958     * as a sequence of <tt>put</tt> invocations on the backing map.
3959     *
3960     * <p>The specified map must be empty at the time this method is invoked,
3961     * and should not be accessed directly after this method returns.  These
3962     * conditions are ensured if the map is created empty, passed directly
3963     * to this method, and no reference to the map is retained, as illustrated
3964     * in the following code fragment:
3965     * <pre>
3966     *    Set&lt;Object&gt; weakHashSet = Collections.newSetFromMap(
3967     *        new WeakHashMap&lt;Object, Boolean&gt;());
3968     * </pre>
3969     *
3970     * @param map the backing map
3971     * @return the set backed by the map
3972     * @throws IllegalArgumentException if <tt>map</tt> is not empty
3973     * @since 1.6
3974     */
3975    public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
3976        return new SetFromMap<>(map);
3977    }
3978
3979    /**
3980     * @serial include
3981     */
3982    private static class SetFromMap<E> extends AbstractSet<E>
3983        implements Set<E>, Serializable
3984    {
3985        private final Map<E, Boolean> m;  // The backing map
3986        private transient Set<E> s;       // Its keySet
3987
3988        SetFromMap(Map<E, Boolean> map) {
3989            if (!map.isEmpty())
3990                throw new IllegalArgumentException("Map is non-empty");
3991            m = map;
3992            s = map.keySet();
3993        }
3994
3995        public void clear()               {        m.clear(); }
3996        public int size()                 { return m.size(); }
3997        public boolean isEmpty()          { return m.isEmpty(); }
3998        public boolean contains(Object o) { return m.containsKey(o); }
3999        public boolean remove(Object o)   { return m.remove(o) != null; }
4000        public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }
4001        public Iterator<E> iterator()     { return s.iterator(); }
4002        public Object[] toArray()         { return s.toArray(); }
4003        public <T> T[] toArray(T[] a)     { return s.toArray(a); }
4004        public String toString()          { return s.toString(); }
4005        public int hashCode()             { return s.hashCode(); }
4006        public boolean equals(Object o)   { return o == this || s.equals(o); }
4007        public boolean containsAll(Collection<?> c) {return s.containsAll(c);}
4008        public boolean removeAll(Collection<?> c)   {return s.removeAll(c);}
4009        public boolean retainAll(Collection<?> c)   {return s.retainAll(c);}
4010        // addAll is the only inherited implementation
4011
4012        private static final long serialVersionUID = 2454657854757543876L;
4013
4014        // Override default methods in Collection
4015        @Override
4016        public void forEach(Consumer<? super E> action) {
4017            s.forEach(action);
4018        }
4019
4020        private void readObject(java.io.ObjectInputStream stream)
4021            throws IOException, ClassNotFoundException
4022        {
4023            stream.defaultReadObject();
4024            s = m.keySet();
4025        }
4026    }
4027
4028    /**
4029     * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo)
4030     * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>,
4031     * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This
4032     * view can be useful when you would like to use a method
4033     * requiring a <tt>Queue</tt> but you need Lifo ordering.
4034     *
4035     * <p>Each method invocation on the queue returned by this method
4036     * results in exactly one method invocation on the backing deque, with
4037     * one exception.  The {@link Queue#addAll addAll} method is
4038     * implemented as a sequence of {@link Deque#addFirst addFirst}
4039     * invocations on the backing deque.
4040     *
4041     * @param deque the deque
4042     * @return the queue
4043     * @since  1.6
4044     */
4045    public static <T> Queue<T> asLifoQueue(Deque<T> deque) {
4046        return new AsLIFOQueue<>(deque);
4047    }
4048
4049    /**
4050     * @serial include
4051     */
4052    static class AsLIFOQueue<E> extends AbstractQueue<E>
4053        implements Queue<E>, Serializable {
4054        private static final long serialVersionUID = 1802017725587941708L;
4055        private final Deque<E> q;
4056        AsLIFOQueue(Deque<E> q)           { this.q = q; }
4057        public boolean add(E e)           { q.addFirst(e); return true; }
4058        public boolean offer(E e)         { return q.offerFirst(e); }
4059        public E poll()                   { return q.pollFirst(); }
4060        public E remove()                 { return q.removeFirst(); }
4061        public E peek()                   { return q.peekFirst(); }
4062        public E element()                { return q.getFirst(); }
4063        public void clear()               {        q.clear(); }
4064        public int size()                 { return q.size(); }
4065        public boolean isEmpty()          { return q.isEmpty(); }
4066        public boolean contains(Object o) { return q.contains(o); }
4067        public boolean remove(Object o)   { return q.remove(o); }
4068        public Iterator<E> iterator()     { return q.iterator(); }
4069        public Object[] toArray()         { return q.toArray(); }
4070        public <T> T[] toArray(T[] a)     { return q.toArray(a); }
4071        public String toString()          { return q.toString(); }
4072        public boolean containsAll(Collection<?> c) {return q.containsAll(c);}
4073        public boolean removeAll(Collection<?> c)   {return q.removeAll(c);}
4074        public boolean retainAll(Collection<?> c)   {return q.retainAll(c);}
4075        // We use inherited addAll; forwarding addAll would be wrong
4076
4077        // Override default methods in Collection
4078        @Override
4079        public void forEach(Consumer<? super E> action) {q.forEach(action);}
4080    }
4081}
4082