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