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