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