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