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