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