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