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