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