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