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