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