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