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