正文:
一、概述:
此类完全由在 collection 上进行操作或返回 collection 的静态方法组成。它包含在 collection 上操作的多态算法,即“包装器”,包装器返回由指定 collection 支持的新 collection,以及少数其他内容。
如果为此类的方法所提供的 collection 或类对象为 null,则这些方法都将抛出 NullPointerException。
此类中所含多态算法的文档通常包括对实现 的简短描述。应该将这类描述视为实现注意事项,而不是规范 的一部分。实现者应该可以随意使用其他算法替代,只要遵循规范本身即可。(例如,sort 使用的算法不一定是合并排序算法,但它必须是稳定的。)
此类中包含的“破坏性”算法,即可修改其所操作的 collection 的算法,该算法被指定在 collection 不支持适当的可变基元(比如 set 方法)时抛出 UnsupportedOperationException。如果调用不会对 collection 产生任何影响,那么这些算法可能(但不要求)抛出此异常。例如,在已经排序的、不可修改列表上调用 sort 方法可能会(也可能不会)抛出 UnsupportedOperationException。
二、拓展点
1,<T> Comparator<T> reverseOrder()分析
源码解释:
返回一个比较器,它强行逆转实现了 Comparable 接口的对象 collection 的自然顺序。
(自然顺序是通过对象自身的 compareTo 方法强行排序的。)
此方法允许使用单个语句,以逆自然顺序对实现了 Comparable 接口的对象 collection(或数组)进行排序(或维护)。
例如,假设 a 是一个字符串数组。那么: Arrays.sort(a, Collections.reverseOrder());
将按照逆字典(字母)顺序对数组进行排序。
1 /** 2 * Returns a comparator that imposes the reverse of the <em>natural 3 * ordering</em> on a collection of objects that implement the 4 * {@code Comparable} interface. (The natural ordering is the ordering 5 * imposed by the objects' own {@code compareTo} method.) This enables a 6 * simple idiom for sorting (or maintaining) collections (or arrays) of 7 * objects that implement the {@code Comparable} interface in 8 * reverse-natural-order. For example, suppose {@code a} is an array of 9 * strings. Then: <pre> 10 * Arrays.sort(a, Collections.reverseOrder()); 11 * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p> 12 * 13 * The returned comparator is serializable. 14 * 15 * @param <T> the class of the objects compared by the comparator 16 * @return A comparator that imposes the reverse of the <i>natural 17 * ordering</i> on a collection of objects that implement 18 * the <tt>Comparable</tt> interface. 19 * @see Comparable 20 */ 21 @SuppressWarnings("unchecked") 22 public static <T> Comparator<T> reverseOrder() { 23 return (Comparator<T>) ReverseComparator.REVERSE_ORDER; 24 } 25 26 /** 27 * @serial include 28 */ 29 private static class ReverseComparator 30 implements Comparator<Comparable<Object>>, Serializable { 31 32 private static final long serialVersionUID = 7207038068494060240L; 33 34 static final ReverseComparator REVERSE_ORDER 35 = new ReverseComparator(); 36 37 public int compare(Comparable<Object> c1, Comparable<Object> c2) { 38 return c2.compareTo(c1); 39 } 40 41 private Object readResolve() { return Collections.reverseOrder(); } 42 43 @Override 44 public Comparator<Comparable<Object>> reversed() { 45 return Comparator.naturalOrder(); 46 } 47 }
示例:
1 public static void main(String[] args) { 2 List<Integer> list = new ArrayList<Integer>(); 3 list.add(1); 4 list.add(5); 5 list.add(2); 6 list.add(3); 7 list.add(6); 8 list.add(4); 9 list.add(7); 10 System.out.println("原顺序:"+list); 11 Collections.sort(list); 12 Comparator<Object> objectComparator = Collections.reverseOrder(); 13 Collections.sort(list,objectComparator); 14 System.out.println("逆转后顺序:"+list); 15 }
结果:
1 原顺序:[1, 5, 2, 3, 6, 4, 7] 2 逆转后顺序:[7, 6, 5, 4, 3, 2, 1]
在调用Collections.reverseOrder() 方法时调用了内部类的构造方法创建 ReverseComparator,
只有在调用 Collections.sort(list,objectComparator)时,逆转比较器作为参数,将调用内部的方法
1 public int compare(Comparable<Object> c1, Comparable<Object> c2) { 2 return c2.compareTo(c1); 3 }
该方法才是顺序逆转的核心!
三、其他源码:
1 public class Collections { 2 // Suppresses default constructor, ensuring non-instantiability. 3 private Collections() { 4 } 5 6 // Algorithms 7 8 /* 9 * Tuning parameters for algorithms - Many of the List algorithms have 10 * two implementations, one of which is appropriate for RandomAccess 11 * lists, the other for "sequential." Often, the random access variant 12 * yields better performance on small sequential access lists. The 13 * tuning parameters below determine the cutoff point for what constitutes 14 * a "small" sequential access list for each algorithm. The values below 15 * were empirically determined to work well for LinkedList. Hopefully 16 * they should be reasonable for other sequential access List 17 * implementations. Those doing performance work on this code would 18 * do well to validate the values of these parameters from time to time. 19 * (The first word of each tuning parameter name is the algorithm to which 20 * it applies.) 21 */ 22 private static final int BINARYSEARCH_THRESHOLD = 5000; 23 private static final int REVERSE_THRESHOLD = 18; 24 private static final int SHUFFLE_THRESHOLD = 5; 25 private static final int FILL_THRESHOLD = 25; 26 private static final int ROTATE_THRESHOLD = 100; 27 private static final int COPY_THRESHOLD = 10; 28 private static final int REPLACEALL_THRESHOLD = 11; 29 private static final int INDEXOFSUBLIST_THRESHOLD = 35; 30 31 /** 32 * Sorts the specified list into ascending order, according to the 33 * {@linkplain Comparable natural ordering} of its elements. 34 * All elements in the list must implement the {@link Comparable} 35 * interface. Furthermore, all elements in the list must be 36 * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} 37 * must not throw a {@code ClassCastException} for any elements 38 * {@code e1} and {@code e2} in the list). 39 * 40 * <p>This sort is guaranteed to be <i>stable</i>: equal elements will 41 * not be reordered as a result of the sort. 42 * 43 * <p>The specified list must be modifiable, but need not be resizable. 44 * 45 * @implNote 46 * This implementation defers to the {@link List#sort(Comparator)} 47 * method using the specified list and a {@code null} comparator. 48 * 49 * @param <T> the class of the objects in the list 50 * @param list the list to be sorted. 51 * @throws ClassCastException if the list contains elements that are not 52 * <i>mutually comparable</i> (for example, strings and integers). 53 * @throws UnsupportedOperationException if the specified list's 54 * list-iterator does not support the {@code set} operation. 55 * @throws IllegalArgumentException (optional) if the implementation 56 * detects that the natural ordering of the list elements is 57 * found to violate the {@link Comparable} contract 58 * @see List#sort(Comparator) 59 */ 60 //根据元素的自然顺序 对指定列表按升序进行排序。列表中的所有元素都必须实现 Comparable 接口 61 @SuppressWarnings("unchecked") 62 public static <T extends Comparable<? super T>> void sort(List<T> list) { 63 list.sort(null); 64 } 65 66 /** 67 * Sorts the specified list according to the order induced by the 68 * specified comparator. All elements in the list must be <i>mutually 69 * comparable</i> using the specified comparator (that is, 70 * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException} 71 * for any elements {@code e1} and {@code e2} in the list). 72 * 73 * <p>This sort is guaranteed to be <i>stable</i>: equal elements will 74 * not be reordered as a result of the sort. 75 * 76 * <p>The specified list must be modifiable, but need not be resizable. 77 * 78 * @implNote 79 * This implementation defers to the {@link List#sort(Comparator)} 80 * method using the specified list and comparator. 81 * 82 * @param <T> the class of the objects in the list 83 * @param list the list to be sorted. 84 * @param c the comparator to determine the order of the list. A 85 * {@code null} value indicates that the elements' <i>natural 86 * ordering</i> should be used. 87 * @throws ClassCastException if the list contains elements that are not 88 * <i>mutually comparable</i> using the specified comparator. 89 * @throws UnsupportedOperationException if the specified list's 90 * list-iterator does not support the {@code set} operation. 91 * @throws IllegalArgumentException (optional) if the comparator is 92 * found to violate the {@link Comparator} contract 93 * @see List#sort(Comparator) 94 */ 95 //根据指定比较器产生的顺序对指定列表进行排序。 96 @SuppressWarnings({"unchecked", "rawtypes"}) 97 public static <T> void sort(List<T> list, Comparator<? super T> c) { 98 list.sort(c); 99 } 100 101 102 /** 103 * Searches the specified list for the specified object using the binary 104 * search algorithm. The list must be sorted into ascending order 105 * according to the {@linkplain Comparable natural ordering} of its 106 * elements (as by the {@link #sort(List)} method) prior to making this 107 * call. If it is not sorted, the results are undefined. If the list 108 * contains multiple elements equal to the specified object, there is no 109 * guarantee which one will be found. 110 * 111 * <p>This method runs in log(n) time for a "random access" list (which 112 * provides near-constant-time positional access). If the specified list 113 * does not implement the {@link RandomAccess} interface and is large, 114 * this method will do an iterator-based binary search that performs 115 * O(n) link traversals and O(log n) element comparisons. 116 * 117 * @param <T> the class of the objects in the list 118 * @param list the list to be searched. 119 * @param key the key to be searched for. 120 * @return the index of the search key, if it is contained in the list; 121 * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The 122 * <i>insertion point</i> is defined as the point at which the 123 * key would be inserted into the list: the index of the first 124 * element greater than the key, or <tt>list.size()</tt> if all 125 * elements in the list are less than the specified key. Note 126 * that this guarantees that the return value will be >= 0 if 127 * and only if the key is found. 128 * @throws ClassCastException if the list contains elements that are not 129 * <i>mutually comparable</i> (for example, strings and 130 * integers), or the search key is not mutually comparable 131 * with the elements of the list. 132 */ 133 //使用二分搜索法搜索指定列表,以获得指定对象。在进行此调用之前,必须根据列表元素的自然顺序对列表进行升序排序(通过 sort(List) //方法)。如果没有对列表进行排序,则结果是不确定的。如果列表包含多个等于指定对象的元素,则无法保证找到的是哪一个。 134 public static <T> 135 int binarySearch(List<? extends Comparable<? super T>> list, T key) { 136 //ArrayList implement RandomAccess,而LinkedList没有实现 RandomAccess,list.size()>5000时使用普通二次搜索查找法消耗的性能过大 137 if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) 138 139 return Collections.indexedBinarySearch(list, key); 140 else 141 return Collections.iteratorBinarySearch(list, key); 142 } 143 144 private static <T> 145 int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) { 146 int low = 0; 147 int high = list.size()-1; 148 149 while (low <= high) { 150 int mid = (low + high) >>> 1; 151 Comparable<? super T> midVal = list.get(mid); 152 int cmp = midVal.compareTo(key); 153 154 if (cmp < 0) 155 low = mid + 1; 156 else if (cmp > 0) 157 high = mid - 1; 158 else 159 return mid; // key found 160 } 161 return -(low + 1); // key not found 162 } 163 164 private static <T> 165 int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key) 166 { 167 int low = 0; 168 int high = list.size()-1; 169 ListIterator<? extends Comparable<? super T>> i = list.listIterator(); 170 171 while (low <= high) { 172 int mid = (low + high) >>> 1; 173 Comparable<? super T> midVal = get(i, mid); 174 int cmp = midVal.compareTo(key); 175 176 if (cmp < 0) 177 low = mid + 1; 178 else if (cmp > 0) 179 high = mid - 1; 180 else 181 return mid; // key found 182 } 183 return -(low + 1); // key not found 184 } 185 186 /** 187 * Gets the ith element from the given list by repositioning the specified 188 * list listIterator. 189 */ 190 private static <T> T get(ListIterator<? extends T> i, int index) { 191 T obj = null; 192 int pos = i.nextIndex(); 193 if (pos <= index) { 194 do { 195 obj = i.next(); 196 } while (pos++ < index); 197 } else { 198 do { 199 obj = i.previous(); 200 } while (--pos > index); 201 } 202 return obj; 203 } 204 205 /** 206 * Searches the specified list for the specified object using the binary 207 * search algorithm. The list must be sorted into ascending order 208 * according to the specified comparator (as by the 209 * {@link #sort(List, Comparator) sort(List, Comparator)} 210 * method), prior to making this call. If it is 211 * not sorted, the results are undefined. If the list contains multiple 212 * elements equal to the specified object, there is no guarantee which one 213 * will be found. 214 * 215 * <p>This method runs in log(n) time for a "random access" list (which 216 * provides near-constant-time positional access). If the specified list 217 * does not implement the {@link RandomAccess} interface and is large, 218 * this method will do an iterator-based binary search that performs 219 * O(n) link traversals and O(log n) element comparisons. 220 * 221 * @param <T> the class of the objects in the list 222 * @param list the list to be searched. 223 * @param key the key to be searched for. 224 * @param c the comparator by which the list is ordered. 225 * A <tt>null</tt> value indicates that the elements' 226 * {@linkplain Comparable natural ordering} should be used. 227 * @return the index of the search key, if it is contained in the list; 228 * otherwise, <tt>(-(<i>insertion point</i>) - 1)</tt>. The 229 * <i>insertion point</i> is defined as the point at which the 230 * key would be inserted into the list: the index of the first 231 * element greater than the key, or <tt>list.size()</tt> if all 232 * elements in the list are less than the specified key. Note 233 * that this guarantees that the return value will be >= 0 if 234 * and only if the key is found. 235 * @throws ClassCastException if the list contains elements that are not 236 * <i>mutually comparable</i> using the specified comparator, 237 * or the search key is not mutually comparable with the 238 * elements of the list using this comparator. 239 */ 240 //使用二分搜索法搜索指定列表,以获得指定对象。在进行此调用之前,必须根据指定的比较器对列表进行升序排序(通过 sort(List, Comparator) //方法)。如果没有对列表进行排序,则结果是不确定的。如果列表包含多个等于指定对象的元素,则无法保证找到的是哪一个。 241 @SuppressWarnings("unchecked") 242 public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) { 243 if (c==null) 244 return binarySearch((List<? extends Comparable<? super T>>) list, key); 245 246 if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) 247 return Collections.indexedBinarySearch(list, key, c); 248 else 249 return Collections.iteratorBinarySearch(list, key, c); 250 } 251 252 private static <T> int indexedBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) { 253 int low = 0; 254 int high = l.size()-1; 255 256 while (low <= high) { 257 int mid = (low + high) >>> 1; 258 T midVal = l.get(mid); 259 int cmp = c.compare(midVal, key); 260 261 if (cmp < 0) 262 low = mid + 1; 263 else if (cmp > 0) 264 high = mid - 1; 265 else 266 return mid; // key found 267 } 268 return -(low + 1); // key not found 269 } 270 271 private static <T> int iteratorBinarySearch(List<? extends T> l, T key, Comparator<? super T> c) { 272 int low = 0; 273 int high = l.size()-1; 274 ListIterator<? extends T> i = l.listIterator(); 275 276 while (low <= high) { 277 int mid = (low + high) >>> 1; 278 T midVal = get(i, mid); 279 int cmp = c.compare(midVal, key); 280 281 if (cmp < 0) 282 low = mid + 1; 283 else if (cmp > 0) 284 high = mid - 1; 285 else 286 return mid; // key found 287 } 288 return -(low + 1); // key not found 289 } 290 291 /** 292 * Reverses the order of the elements in the specified list.<p> 293 * 294 * This method runs in linear time. 295 * 296 * @param list the list whose elements are to be reversed. 297 * @throws UnsupportedOperationException if the specified list or 298 * its list-iterator does not support the <tt>set</tt> operation. 299 */ 300 //反转指定列表中元素的顺序。 301 @SuppressWarnings({"rawtypes", "unchecked"}) 302 public static void reverse(List<?> list) { 303 int size = list.size(); 304 if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) { 305 for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--) 306 swap(list, i, j); 307 } else { 308 // instead of using a raw type here, it's possible to capture 309 // the wildcard but it will require a call to a supplementary 310 // private method 311 ListIterator fwd = list.lis tIterator(); 312 ListIterator rev = list.listIterator(size); 313 for (int i=0, mid=list.size()>>1; i<mid; i++) { 314 Object tmp = fwd.next(); 315 fwd.set(rev.previous()); 316 rev.set(tmp); 317 } 318 } 319 } 320 321 /** 322 * Randomly permutes the specified list using a default source of 323 * randomness. All permutations occur with approximately equal 324 * likelihood. 325 * 326 * <p>The hedge "approximately" is used in the foregoing description because 327 * default source of randomness is only approximately an unbiased source 328 * of independently chosen bits. If it were a perfect source of randomly 329 * chosen bits, then the algorithm would choose permutations with perfect 330 * uniformity. 331 * 332 * <p>This implementation traverses the list backwards, from the last 333 * element up to the second, repeatedly swapping a randomly selected element 334 * into the "current position". Elements are randomly selected from the 335 * portion of the list that runs from the first element to the current 336 * position, inclusive. 337 * 338 * <p>This method runs in linear time. If the specified list does not 339 * implement the {@link RandomAccess} interface and is large, this 340 * implementation dumps the specified list into an array before shuffling 341 * it, and dumps the shuffled array back into the list. This avoids the 342 * quadratic behavior that would result from shuffling a "sequential 343 * access" list in place. 344 * 345 * @param list the list to be shuffled. 346 * @throws UnsupportedOperationException if the specified list or 347 * its list-iterator does not support the <tt>set</tt> operation. 348 */ 349 //使用默认随机源对指定列表进行置换。所有置换发生的可能性都是大致相等的。 350 //此实现向后遍历列表,从最后一个元素一直到第二个元素,将随机选择的元素重复交换到“当前位置”。 351 //元素是从列表的一部分随机选择的,该部分列表从第一个元素一直到当前位置(包括)。 352 //此方法以线性时间运行。如果指定列表没有实现 RandomAccess 接口并且是一个大型列表,则此实现在改组列表前将指定列表转储到数组中, 353 //并将改组后的数组转储回列表中。这避免了二次行为,该行为是原地改组一个“有序访问”列表引起的。 354 public static void shuffle(List<?> list) { 355 Random rnd = r; 356 if (rnd == null) 357 r = rnd = new Random(); // harmless race. 358 shuffle(list, rnd); 359 } 360 361 private static Random r; 362 363 /** 364 * Randomly permute the specified list using the specified source of 365 * randomness. All permutations occur with equal likelihood 366 * assuming that the source of randomness is fair.<p> 367 * 368 * This implementation traverses the list backwards, from the last element 369 * up to the second, repeatedly swapping a randomly selected element into 370 * the "current position". Elements are randomly selected from the 371 * portion of the list that runs from the first element to the current 372 * position, inclusive.<p> 373 * 374 * This method runs in linear time. If the specified list does not 375 * implement the {@link RandomAccess} interface and is large, this 376 * implementation dumps the specified list into an array before shuffling 377 * it, and dumps the shuffled array back into the list. This avoids the 378 * quadratic behavior that would result from shuffling a "sequential 379 * access" list in place. 380 * 381 * @param list the list to be shuffled. 382 * @param rnd the source of randomness to use to shuffle the list. 383 * @throws UnsupportedOperationException if the specified list or its 384 * list-iterator does not support the <tt>set</tt> operation. 385 */ 386 //使用指定的随机源对指定列表进行置换。所有置换发生的可能性都是相等的,假定随机源是公平的。 387 //同方法:shuffle(List<?> list) 388 @SuppressWarnings({"rawtypes", "unchecked"}) 389 public static void shuffle(List<?> list, Random rnd) { 390 int size = list.size(); 391 if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { 392 for (int i=size; i>1; i--) 393 swap(list, i-1, rnd.nextInt(i)); 394 } else { 395 Object arr[] = list.toArray(); 396 397 // Shuffle array 398 for (int i=size; i>1; i--) 399 swap(arr, i-1, rnd.nextInt(i)); 400 401 // Dump array back into list 402 // instead of using a raw type here, it's possible to capture 403 // the wildcard but it will require a call to a supplementary 404 // private method 405 ListIterator it = list.listIterator(); 406 for (int i=0; i<arr.length; i++) { 407 it.next(); 408 it.set(arr[i]); 409 } 410 } 411 } 412 413 /** 414 * Swaps the elements at the specified positions in the specified list. 415 * (If the specified positions are equal, invoking this method leaves 416 * the list unchanged.) 417 * 418 * @param list The list in which to swap elements. 419 * @param i the index of one element to be swapped. 420 * @param j the index of the other element to be swapped. 421 * @throws IndexOutOfBoundsException if either <tt>i</tt> or <tt>j</tt> 422 * is out of range (i < 0 || i >= list.size() 423 * || j < 0 || j >= list.size()). 424 * @since 1.4 425 */ 426 //在指定列表的指定位置处交换元素 427 @SuppressWarnings({"rawtypes", "unchecked"}) 428 public static void swap(List<?> list, int i, int j) { 429 // instead of using a raw type here, it's possible to capture 430 // the wildcard but it will require a call to a supplementary 431 // private method 432 final List l = list; 433 l.set(i, l.set(j, l.get(i))); 434 } 435 436 /** 437 * Swaps the two specified elements in the specified array. 438 */ 439 private static void swap(Object[] arr, int i, int j) { 440 Object tmp = arr[i]; 441 arr[i] = arr[j]; 442 arr[j] = tmp; 443 } 444 445 /** 446 * Replaces all of the elements of the specified list with the specified 447 * element. <p> 448 * 449 * This method runs in linear time. 450 * 451 * @param <T> the class of the objects in the list 452 * @param list the list to be filled with the specified element. 453 * @param obj The element with which to fill the specified list. 454 * @throws UnsupportedOperationException if the specified list or its 455 * list-iterator does not support the <tt>set</tt> operation. 456 */ 457 //使用指定元素替换指定列表中的所有元素。 458 public static <T> void fill(List<? super T> list, T obj) { 459 int size = list.size(); 460 461 if (size < FILL_THRESHOLD || list instanceof RandomAccess) { 462 for (int i=0; i<size; i++) 463 list.set(i, obj); 464 } else { 465 ListIterator<? super T> itr = list.listIterator(); 466 for (int i=0; i<size; i++) { 467 itr.next(); 468 itr.set(obj); 469 } 470 } 471 } 472 473 /** 474 * Copies all of the elements from one list into another. After the 475 * operation, the index of each copied element in the destination list 476 * will be identical to its index in the source list. The destination 477 * list must be at least as long as the source list. If it is longer, the 478 * remaining elements in the destination list are unaffected. <p> 479 * 480 * This method runs in linear time. 481 * 482 * @param <T> the class of the objects in the lists 483 * @param dest The destination list. 484 * @param src The source list. 485 * @throws IndexOutOfBoundsException if the destination list is too small 486 * to contain the entire source List. 487 * @throws UnsupportedOperationException if the destination list's 488 * list-iterator does not support the <tt>set</tt> operation. 489 */ 490 //将所有元素从一个列表复制到另一个列表 491 //目标列表的长度至少必须等于源列表。 492 public static <T> void copy(List<? super T> dest, List<? extends T> src) { 493 int srcSize = src.size(); 494 if (srcSize > dest.size()) 495 throw new IndexOutOfBoundsException("Source does not fit in dest"); 496 497 if (srcSize < COPY_THRESHOLD || 498 (src instanceof RandomAccess && dest instanceof RandomAccess)) { 499 for (int i=0; i<srcSize; i++) 500 dest.set(i, src.get(i)); 501 } else { 502 ListIterator<? super T> di=dest.listIterator(); 503 ListIterator<? extends T> si=src.listIterator(); 504 for (int i=0; i<srcSize; i++) { 505 di.next(); 506 di.set(si.next()); 507 } 508 } 509 } 510 511 /** 512 * Returns the minimum element of the given collection, according to the 513 * <i>natural ordering</i> of its elements. All elements in the 514 * collection must implement the <tt>Comparable</tt> interface. 515 * Furthermore, all elements in the collection must be <i>mutually 516 * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a 517 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and 518 * <tt>e2</tt> in the collection).<p> 519 * 520 * This method iterates over the entire collection, hence it requires 521 * time proportional to the size of the collection. 522 * 523 * @param <T> the class of the objects in the collection 524 * @param coll the collection whose minimum element is to be determined. 525 * @return the minimum element of the given collection, according 526 * to the <i>natural ordering</i> of its elements. 527 * @throws ClassCastException if the collection contains elements that are 528 * not <i>mutually comparable</i> (for example, strings and 529 * integers). 530 * @throws NoSuchElementException if the collection is empty. 531 * @see Comparable 532 */ 533 //根据元素的自然顺序 返回给定 collection 的最小元素。collection 中的所有元素都必须实现 Comparable 接口。 534 public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) { 535 Iterator<? extends T> i = coll.iterator(); 536 T candidate = i.next(); 537 538 while (i.hasNext()) { 539 T next = i.next(); 540 if (next.compareTo(candidate) < 0) 541 candidate = next; 542 } 543 return candidate; 544 } 545 546 /** 547 * Returns the minimum element of the given collection, according to the 548 * order induced by the specified comparator. All elements in the 549 * collection must be <i>mutually comparable</i> by the specified 550 * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a 551 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and 552 * <tt>e2</tt> in the collection).<p> 553 * 554 * This method iterates over the entire collection, hence it requires 555 * time proportional to the size of the collection. 556 * 557 * @param <T> the class of the objects in the collection 558 * @param coll the collection whose minimum element is to be determined. 559 * @param comp the comparator with which to determine the minimum element. 560 * A <tt>null</tt> value indicates that the elements' <i>natural 561 * ordering</i> should be used. 562 * @return the minimum element of the given collection, according 563 * to the specified comparator. 564 * @throws ClassCastException if the collection contains elements that are 565 * not <i>mutually comparable</i> using the specified comparator. 566 * @throws NoSuchElementException if the collection is empty. 567 * @see Comparable 568 */ 569 //根据指定比较器产生的顺序,返回给定 collection 的最小元素。同min 570 @SuppressWarnings({"unchecked", "rawtypes"}) 571 public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) { 572 if (comp==null) 573 return (T)min((Collection) coll); 574 575 Iterator<? extends T> i = coll.iterator(); 576 T candidate = i.next(); 577 578 while (i.hasNext()) { 579 T next = i.next(); 580 if (comp.compare(next, candidate) < 0) 581 candidate = next; 582 } 583 return candidate; 584 } 585 586 /** 587 * Returns the maximum element of the given collection, according to the 588 * <i>natural ordering</i> of its elements. All elements in the 589 * collection must implement the <tt>Comparable</tt> interface. 590 * Furthermore, all elements in the collection must be <i>mutually 591 * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a 592 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and 593 * <tt>e2</tt> in the collection).<p> 594 * 595 * This method iterates over the entire collection, hence it requires 596 * time proportional to the size of the collection. 597 * 598 * @param <T> the class of the objects in the collection 599 * @param coll the collection whose maximum element is to be determined. 600 * @return the maximum element of the given collection, according 601 * to the <i>natural ordering</i> of its elements. 602 * @throws ClassCastException if the collection contains elements that are 603 * not <i>mutually comparable</i> (for example, strings and 604 * integers). 605 * @throws NoSuchElementException if the collection is empty. 606 * @see Comparable 607 */ 608 //根据元素的自然顺序,返回给定 collection 的最大元素。同min 609 public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { 610 Iterator<? extends T> i = coll.iterator(); 611 T candidate = i.next(); 612 613 while (i.hasNext()) { 614 T next = i.next(); 615 if (next.compareTo(candidate) > 0) 616 candidate = next; 617 } 618 return candidate; 619 } 620 621 /** 622 * Returns the maximum element of the given collection, according to the 623 * order induced by the specified comparator. All elements in the 624 * collection must be <i>mutually comparable</i> by the specified 625 * comparator (that is, <tt>comp.compare(e1, e2)</tt> must not throw a 626 * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and 627 * <tt>e2</tt> in the collection).<p> 628 * 629 * This method iterates over the entire collection, hence it requires 630 * time proportional to the size of the collection. 631 * 632 * @param <T> the class of the objects in the collection 633 * @param coll the collection whose maximum element is to be determined. 634 * @param comp the comparator with which to determine the maximum element. 635 * A <tt>null</tt> value indicates that the elements' <i>natural 636 * ordering</i> should be used. 637 * @return the maximum element of the given collection, according 638 * to the specified comparator. 639 * @throws ClassCastException if the collection contains elements that are 640 * not <i>mutually comparable</i> using the specified comparator. 641 * @throws NoSuchElementException if the collection is empty. 642 * @see Comparable 643 */ 644 //根据指定比较器产生的顺序,返回给定 collection 的最大元素。同min 645 @SuppressWarnings({"unchecked", "rawtypes"}) 646 public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) { 647 if (comp==null) 648 return (T)max((Collection) coll); 649 650 Iterator<? extends T> i = coll.iterator(); 651 T candidate = i.next(); 652 653 while (i.hasNext()) { 654 T next = i.next(); 655 if (comp.compare(next, candidate) > 0) 656 candidate = next; 657 } 658 return candidate; 659 } 660 661 /** 662 * Rotates the elements in the specified list by the specified distance. 663 * After calling this method, the element at index <tt>i</tt> will be 664 * the element previously at index <tt>(i - distance)</tt> mod 665 * <tt>list.size()</tt>, for all values of <tt>i</tt> between <tt>0</tt> 666 * and <tt>list.size()-1</tt>, inclusive. (This method has no effect on 667 * the size of the list.) 668 * 669 * <p>For example, suppose <tt>list</tt> comprises<tt> [t, a, n, k, s]</tt>. 670 * After invoking <tt>Collections.rotate(list, 1)</tt> (or 671 * <tt>Collections.rotate(list, -4)</tt>), <tt>list</tt> will comprise 672 * <tt>[s, t, a, n, k]</tt>. 673 * 674 * <p>Note that this method can usefully be applied to sublists to 675 * move one or more elements within a list while preserving the 676 * order of the remaining elements. For example, the following idiom 677 * moves the element at index <tt>j</tt> forward to position 678 * <tt>k</tt> (which must be greater than or equal to <tt>j</tt>): 679 * <pre> 680 * Collections.rotate(list.subList(j, k+1), -1); 681 * </pre> 682 * To make this concrete, suppose <tt>list</tt> comprises 683 * <tt>[a, b, c, d, e]</tt>. To move the element at index <tt>1</tt> 684 * (<tt>b</tt>) forward two positions, perform the following invocation: 685 * <pre> 686 * Collections.rotate(l.subList(1, 4), -1); 687 * </pre> 688 * The resulting list is <tt>[a, c, d, b, e]</tt>. 689 * 690 * <p>To move more than one element forward, increase the absolute value 691 * of the rotation distance. To move elements backward, use a positive 692 * shift distance. 693 * 694 * <p>If the specified list is small or implements the {@link 695 * RandomAccess} interface, this implementation exchanges the first 696 * element into the location it should go, and then repeatedly exchanges 697 * the displaced element into the location it should go until a displaced 698 * element is swapped into the first element. If necessary, the process 699 * is repeated on the second and successive elements, until the rotation 700 * is complete. If the specified list is large and doesn't implement the 701 * <tt>RandomAccess</tt> interface, this implementation breaks the 702 * list into two sublist views around index <tt>-distance mod size</tt>. 703 * Then the {@link #reverse(List)} method is invoked on each sublist view, 704 * and finally it is invoked on the entire list. For a more complete 705 * description of both algorithms, see Section 2.3 of Jon Bentley's 706 * <i>Programming Pearls</i> (Addison-Wesley, 1986). 707 * 708 * @param list the list to be rotated. 709 * @param distance the distance to rotate the list. There are no 710 * constraints on this value; it may be zero, negative, or 711 * greater than <tt>list.size()</tt>. 712 * @throws UnsupportedOperationException if the specified list or 713 * its list-iterator does not support the <tt>set</tt> operation. 714 * @since 1.4 715 */ 716 //根据指定的距离轮换指定列表中的元素。 717 public static void rotate(List<?> list, int distance) { 718 if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD) 719 rotate1(list, distance); 720 else 721 rotate2(list, distance); 722 } 723 724 示例:会改变list的数据结构 725 public static void main(String[] args) { 726 List<Integer> list = new ArrayList<Integer>(); 727 list.add(0); 728 list.add(1); 729 list.add(2); 730 list.add(3); 731 list.add(4); 732 list.add(5); 733 System.out.println(list); 734 List<Integer> integers = list.subList(1, 4); 735 System.out.println(integers); 736 Collections.rotate(integers,1); 737 System.out.println(list); 738 } 739 740 结果: 741 [0, 1, 2, 3, 4, 5] 742 [1, 2, 3] 743 [0, 3, 1, 2, 4, 5] 744 745 private static <T> void rotate1(List<T> list, int distance) { 746 int size = list.size(); 747 if (size == 0) 748 return; 749 distance = distance % size; 750 if (distance < 0) 751 distance += size; 752 if (distance == 0) 753 return; 754 755 for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) { 756 T displaced = list.get(cycleStart); 757 int i = cycleStart; 758 do { 759 i += distance; 760 if (i >= size) 761 i -= size; 762 displaced = list.set(i, displaced); 763 nMoved ++; 764 } while (i != cycleStart); 765 } 766 } 767 768 private static void rotate2(List<?> list, int distance) { 769 int size = list.size(); 770 if (size == 0) 771 return; 772 int mid = -distance % size; 773 if (mid < 0) 774 mid += size; 775 if (mid == 0) 776 return; 777 778 reverse(list.subList(0, mid)); 779 reverse(list.subList(mid, size)); 780 reverse(list); 781 } 782 783 /** 784 * Replaces all occurrences of one specified value in a list with another. 785 * More formally, replaces with <tt>newVal</tt> each element <tt>e</tt> 786 * in <tt>list</tt> such that 787 * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>. 788 * (This method has no effect on the size of the list.) 789 * 790 * @param <T> the class of the objects in the list 791 * @param list the list in which replacement is to occur. 792 * @param oldVal the old value to be replaced. 793 * @param newVal the new value with which <tt>oldVal</tt> is to be 794 * replaced. 795 * @return <tt>true</tt> if <tt>list</tt> contained one or more elements 796 * <tt>e</tt> such that 797 * <tt>(oldVal==null ? e==null : oldVal.equals(e))</tt>. 798 * @throws UnsupportedOperationException if the specified list or 799 * its list-iterator does not support the <tt>set</tt> operation. 800 * @since 1.4 801 */ 802 //使用另一个值替换列表中出现的所有某一指定值。 803 //更确切地讲,使用 newVal 替换 list 中满足 (oldVal==null ? e==null : oldVal.equals(e)) 的每个 e 元素。 804 public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) { 805 boolean result = false; 806 int size = list.size(); 807 if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) { 808 if (oldVal==null) { 809 for (int i=0; i<size; i++) { 810 if (list.get(i)==null) { 811 list.set(i, newVal); 812 result = true; 813 } 814 } 815 } else { 816 for (int i=0; i<size; i++) { 817 if (oldVal.equals(list.get(i))) { 818 list.set(i, newVal); 819 result = true; 820 } 821 } 822 } 823 } else { 824 ListIterator<T> itr=list.listIterator(); 825 if (oldVal==null) { 826 for (int i=0; i<size; i++) { 827 if (itr.next()==null) { 828 itr.set(newVal); 829 result = true; 830 } 831 } 832 } else { 833 for (int i=0; i<size; i++) { 834 if (oldVal.equals(itr.next())) { 835 itr.set(newVal); 836 result = true; 837 } 838 } 839 } 840 } 841 return result; 842 } 843 844 /** 845 * Returns the starting position of the first occurrence of the specified 846 * target list within the specified source list, or -1 if there is no 847 * such occurrence. More formally, returns the lowest index <tt>i</tt> 848 * such that {@code source.subList(i, i+target.size()).equals(target)}, 849 * or -1 if there is no such index. (Returns -1 if 850 * {@code target.size() > source.size()}) 851 * 852 * <p>This implementation uses the "brute force" technique of scanning 853 * over the source list, looking for a match with the target at each 854 * location in turn. 855 * 856 * @param source the list in which to search for the first occurrence 857 * of <tt>target</tt>. 858 * @param target the list to search for as a subList of <tt>source</tt>. 859 * @return the starting position of the first occurrence of the specified 860 * target list within the specified source list, or -1 if there 861 * is no such occurrence. 862 * @since 1.4 863 */ 864 //返回指定源列表中第一次出现指定目标列表的起始位置;如果没有出现这样的列表,则返回 -1。 865 public static int indexOfSubList(List<?> source, List<?> target) { 866 int sourceSize = source.size(); 867 int targetSize = target.size(); 868 int maxCandidate = sourceSize - targetSize; 869 870 if (sourceSize < INDEXOFSUBLIST_THRESHOLD || 871 (source instanceof RandomAccess&&target instanceof RandomAccess)) { 872 nextCand: 873 for (int candidate = 0; candidate <= maxCandidate; candidate++) { 874 for (int i=0, j=candidate; i<targetSize; i++, j++) 875 if (!eq(target.get(i), source.get(j))) 876 continue nextCand; // Element mismatch, try next cand 877 return candidate; // All elements of candidate matched target 878 } 879 } else { // Iterator version of above algorithm 880 ListIterator<?> si = source.listIterator(); 881 nextCand: 882 for (int candidate = 0; candidate <= maxCandidate; candidate++) { 883 ListIterator<?> ti = target.listIterator(); 884 for (int i=0; i<targetSize; i++) { 885 if (!eq(ti.next(), si.next())) { 886 // Back up source iterator to next candidate 887 for (int j=0; j<i; j++) 888 si.previous(); 889 continue nextCand; 890 } 891 } 892 return candidate; 893 } 894 } 895 return -1; // No candidate matched the target 896 } 897 898 /** 899 * Returns the starting position of the last occurrence of the specified 900 * target list within the specified source list, or -1 if there is no such 901 * occurrence. More formally, returns the highest index <tt>i</tt> 902 * such that {@code source.subList(i, i+target.size()).equals(target)}, 903 * or -1 if there is no such index. (Returns -1 if 904 * {@code target.size() > source.size()}) 905 * 906 * <p>This implementation uses the "brute force" technique of iterating 907 * over the source list, looking for a match with the target at each 908 * location in turn. 909 * 910 * @param source the list in which to search for the last occurrence 911 * of <tt>target</tt>. 912 * @param target the list to search for as a subList of <tt>source</tt>. 913 * @return the starting position of the last occurrence of the specified 914 * target list within the specified source list, or -1 if there 915 * is no such occurrence. 916 * @since 1.4 917 */ 918 //返回指定源列表中最后一次出现指定目标列表的起始位置;如果没有出现这样的列表,则返回 -1。 919 public static int lastIndexOfSubList(List<?> source, List<?> target) { 920 int sourceSize = source.size(); 921 int targetSize = target.size(); 922 int maxCandidate = sourceSize - targetSize; 923 924 if (sourceSize < INDEXOFSUBLIST_THRESHOLD || 925 source instanceof RandomAccess) { // Index access version 926 nextCand: 927 for (int candidate = maxCandidate; candidate >= 0; candidate--) { 928 for (int i=0, j=candidate; i<targetSize; i++, j++) 929 if (!eq(target.get(i), source.get(j))) 930 continue nextCand; // Element mismatch, try next cand 931 return candidate; // All elements of candidate matched target 932 } 933 } else { // Iterator version of above algorithm 934 if (maxCandidate < 0) 935 return -1; 936 ListIterator<?> si = source.listIterator(maxCandidate); 937 nextCand: 938 for (int candidate = maxCandidate; candidate >= 0; candidate--) { 939 ListIterator<?> ti = target.listIterator(); 940 for (int i=0; i<targetSize; i++) { 941 if (!eq(ti.next(), si.next())) { 942 if (candidate != 0) { 943 // Back up source iterator to next candidate 944 for (int j=0; j<=i+1; j++) 945 si.previous(); 946 } 947 continue nextCand; 948 } 949 } 950 return candidate; 951 } 952 } 953 return -1; // No candidate matched the target 954 } 955 956 957 // Unmodifiable Wrappers 958 959 /** 960 * Returns an unmodifiable view of the specified collection. This method 961 * allows modules to provide users with "read-only" access to internal 962 * collections. Query operations on the returned collection "read through" 963 * to the specified collection, and attempts to modify the returned 964 * collection, whether direct or via its iterator, result in an 965 * <tt>UnsupportedOperationException</tt>.<p> 966 * 967 * The returned collection does <i>not</i> pass the hashCode and equals 968 * operations through to the backing collection, but relies on 969 * <tt>Object</tt>'s <tt>equals</tt> and <tt>hashCode</tt> methods. This 970 * is necessary to preserve the contracts of these operations in the case 971 * that the backing collection is a set or a list.<p> 972 * 973 * The returned collection will be serializable if the specified collection 974 * is serializable. 975 * 976 * @param <T> the class of the objects in the collection 977 * @param c the collection for which an unmodifiable view is to be 978 * returned. 979 * @return an unmodifiable view of the specified collection. 980 */ 981 //返回指定 collection 的不可修改视图。此方法允许模块为用户提供对内部 collection 的“只读”访问。 982 //在返回的 collection 上执行的查询操作将“读完”指定的 collection。 983 //人为的给普通容器加上不可修改的特性 984 public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) { 985 return new UnmodifiableCollection<>(c); 986 } 987 988 /** 989 * @serial include 990 */ 991 static class UnmodifiableCollection<E> implements Collection<E>, Serializable { 992 private static final long serialVersionUID = 1820017752578914078L; 993 994 final Collection<? extends E> c; 995 996 UnmodifiableCollection(Collection<? extends E> c) { 997 if (c==null) 998 throw new NullPointerException(); 999 this.c = c; 1000 } 1001 1002 public int size() {return c.size();} 1003 public boolean isEmpty() {return c.isEmpty();} 1004 public boolean contains(Object o) {return c.contains(o);} 1005 public Object[] toArray() {return c.toArray();} 1006 public <T> T[] toArray(T[] a) {return c.toArray(a);} 1007 public String toString() {return c.toString();} 1008 1009 public Iterator<E> iterator() { 1010 return new Iterator<E>() { 1011 private final Iterator<? extends E> i = c.iterator(); 1012 1013 public boolean hasNext() {return i.hasNext();} 1014 public E next() {return i.next();} 1015 public void remove() { 1016 throw new UnsupportedOperationException(); 1017 } 1018 @Override 1019 public void forEachRemaining(Consumer<? super E> action) { 1020 // Use backing collection version 1021 i.forEachRemaining(action); 1022 } 1023 }; 1024 } 1025 1026 public boolean add(E e) { 1027 throw new UnsupportedOperationException(); 1028 } 1029 public boolean remove(Object o) { 1030 throw new UnsupportedOperationException(); 1031 } 1032 1033 public boolean containsAll(Collection<?> coll) { 1034 return c.containsAll(coll); 1035 } 1036 public boolean addAll(Collection<? extends E> coll) { 1037 throw new UnsupportedOperationException(); 1038 } 1039 public boolean removeAll(Collection<?> coll) { 1040 throw new UnsupportedOperationException(); 1041 } 1042 public boolean retainAll(Collection<?> coll) { 1043 throw new UnsupportedOperationException(); 1044 } 1045 public void clear() { 1046 throw new UnsupportedOperationException(); 1047 } 1048 1049 // Override default methods in Collection 1050 @Override 1051 public void forEach(Consumer<? super E> action) { 1052 c.forEach(action); 1053 } 1054 @Override 1055 public boolean removeIf(Predicate<? super E> filter) { 1056 throw new UnsupportedOperationException(); 1057 } 1058 @SuppressWarnings("unchecked") 1059 @Override 1060 public Spliterator<E> spliterator() { 1061 return (Spliterator<E>)c.spliterator(); 1062 } 1063 @SuppressWarnings("unchecked") 1064 @Override 1065 public Stream<E> stream() { 1066 return (Stream<E>)c.stream(); 1067 } 1068 @SuppressWarnings("unchecked") 1069 @Override 1070 public Stream<E> parallelStream() { 1071 return (Stream<E>)c.parallelStream(); 1072 } 1073 } 1074 1075 /** 1076 * Returns an unmodifiable view of the specified set. This method allows 1077 * modules to provide users with "read-only" access to internal sets. 1078 * Query operations on the returned set "read through" to the specified 1079 * set, and attempts to modify the returned set, whether direct or via its 1080 * iterator, result in an <tt>UnsupportedOperationException</tt>.<p> 1081 * 1082 * The returned set will be serializable if the specified set 1083 * is serializable. 1084 * 1085 * @param <T> the class of the objects in the set 1086 * @param s the set for which an unmodifiable view is to be returned. 1087 * @return an unmodifiable view of the specified set. 1088 */ 1089 //返回指定 set 的不可修改视图。此方法允许模块为用户提供对内部 set 的“只读”访问。 1090 //在返回的 set 上执行的查询操作将“读完”指定的 set。 1091 public static <T> Set<T> unmodifiableSet(Set<? extends T> s) { 1092 return new UnmodifiableSet<>(s); 1093 } 1094 1095 /** 1096 * @serial include 1097 */ 1098 static class UnmodifiableSet<E> extends UnmodifiableCollection<E> 1099 implements Set<E>, Serializable { 1100 private static final long serialVersionUID = -9215047833775013803L; 1101 1102 UnmodifiableSet(Set<? extends E> s) {super(s);} 1103 public boolean equals(Object o) {return o == this || c.equals(o);} 1104 public int hashCode() {return c.hashCode();} 1105 } 1106 1107 /** 1108 * Returns an unmodifiable view of the specified sorted set. This method 1109 * allows modules to provide users with "read-only" access to internal 1110 * sorted sets. Query operations on the returned sorted set "read 1111 * through" to the specified sorted set. Attempts to modify the returned 1112 * sorted set, whether direct, via its iterator, or via its 1113 * <tt>subSet</tt>, <tt>headSet</tt>, or <tt>tailSet</tt> views, result in 1114 * an <tt>UnsupportedOperationException</tt>.<p> 1115 * 1116 * The returned sorted set will be serializable if the specified sorted set 1117 * is serializable. 1118 * 1119 * @param <T> the class of the objects in the set 1120 * @param s the sorted set for which an unmodifiable view is to be 1121 * returned. 1122 * @return an unmodifiable view of the specified sorted set. 1123 */ 1124 //返回指定有序 set 的不可修改视图。此方法允许模块为用户提供对内部有序 set 的“只读”访问。 1125 //在返回的有序 set 上执行的查询操作将“读完”指定的有序 set。 1126 public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) { 1127 return new UnmodifiableSortedSet<>(s); 1128 } 1129 1130 /** 1131 * @serial include 1132 */ 1133 static class UnmodifiableSortedSet<E> 1134 extends UnmodifiableSet<E> 1135 implements SortedSet<E>, Serializable { 1136 private static final long serialVersionUID = -4929149591599911165L; 1137 private final SortedSet<E> ss; 1138 1139 UnmodifiableSortedSet(SortedSet<E> s) {super(s); ss = s;} 1140 1141 public Comparator<? super E> comparator() {return ss.comparator();} 1142 1143 public SortedSet<E> subSet(E fromElement, E toElement) { 1144 return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement)); 1145 } 1146 public SortedSet<E> headSet(E toElement) { 1147 return new UnmodifiableSortedSet<>(ss.headSet(toElement)); 1148 } 1149 public SortedSet<E> tailSet(E fromElement) { 1150 return new UnmodifiableSortedSet<>(ss.tailSet(fromElement)); 1151 } 1152 1153 public E first() {return ss.first();} 1154 public E last() {return ss.last();} 1155 } 1156 1157 1158 1159 1160 1161 1162 // Synch Wrappers 1163 1164 /** 1165 * Returns a synchronized (thread-safe) collection backed by the specified 1166 * collection. In order to guarantee serial access, it is critical that 1167 * <strong>all</strong> access to the backing collection is accomplished 1168 * through the returned collection.<p> 1169 * 1170 * It is imperative that the user manually synchronize on the returned 1171 * collection when traversing it via {@link Iterator}, {@link Spliterator} 1172 * or {@link Stream}: 1173 * <pre> 1174 * Collection c = Collections.synchronizedCollection(myCollection); 1175 * ... 1176 * synchronized (c) { 1177 * Iterator i = c.iterator(); // Must be in the synchronized block 1178 * while (i.hasNext()) 1179 * foo(i.next()); 1180 * } 1181 * </pre> 1182 * Failure to follow this advice may result in non-deterministic behavior. 1183 * 1184 * <p>The returned collection does <i>not</i> pass the {@code hashCode} 1185 * and {@code equals} operations through to the backing collection, but 1186 * relies on {@code Object}'s equals and hashCode methods. This is 1187 * necessary to preserve the contracts of these operations in the case 1188 * that the backing collection is a set or a list.<p> 1189 * 1190 * The returned collection will be serializable if the specified collection 1191 * is serializable. 1192 * 1193 * @param <T> the class of the objects in the collection 1194 * @param c the collection to be "wrapped" in a synchronized collection. 1195 * @return a synchronized view of the specified collection. 1196 */ 1197 //返回指定 collection 支持的同步(线程安全的)collection。 1198 //为了保证按顺序访问,必须通过返回的 collection 完成所有对底层实现 collection 的访问。 1199 public static <T> Collection<T> synchronizedCollection(Collection<T> c) { 1200 return new SynchronizedCollection<>(c); 1201 } 1202 1203 static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) { 1204 return new SynchronizedCollection<>(c, mutex); 1205 } 1206 1207 /** 1208 * @serial include 1209 */ 1210 static class SynchronizedCollection<E> implements Collection<E>, Serializable { 1211 private static final long serialVersionUID = 3053995032091335093L; 1212 1213 final Collection<E> c; // Backing Collection 1214 final Object mutex; // Object on which to synchronize 1215 1216 SynchronizedCollection(Collection<E> c) { 1217 this.c = Objects.requireNonNull(c); 1218 mutex = this; 1219 } 1220 1221 SynchronizedCollection(Collection<E> c, Object mutex) { 1222 this.c = Objects.requireNonNull(c); 1223 this.mutex = Objects.requireNonNull(mutex); 1224 } 1225 1226 public int size() { 1227 synchronized (mutex) {return c.size();} 1228 } 1229 public boolean isEmpty() { 1230 synchronized (mutex) {return c.isEmpty();} 1231 } 1232 public boolean contains(Object o) { 1233 synchronized (mutex) {return c.contains(o);} 1234 } 1235 public Object[] toArray() { 1236 synchronized (mutex) {return c.toArray();} 1237 } 1238 public <T> T[] toArray(T[] a) { 1239 synchronized (mutex) {return c.toArray(a);} 1240 } 1241 1242 public Iterator<E> iterator() { 1243 return c.iterator(); // Must be manually synched by user! 1244 } 1245 1246 public boolean add(E e) { 1247 synchronized (mutex) {return c.add(e);} 1248 } 1249 public boolean remove(Object o) { 1250 synchronized (mutex) {return c.remove(o);} 1251 } 1252 1253 public boolean containsAll(Collection<?> coll) { 1254 synchronized (mutex) {return c.containsAll(coll);} 1255 } 1256 public boolean addAll(Collection<? extends E> coll) { 1257 synchronized (mutex) {return c.addAll(coll);} 1258 } 1259 public boolean removeAll(Collection<?> coll) { 1260 synchronized (mutex) {return c.removeAll(coll);} 1261 } 1262 public boolean retainAll(Collection<?> coll) { 1263 synchronized (mutex) {return c.retainAll(coll);} 1264 } 1265 public void clear() { 1266 synchronized (mutex) {c.clear();} 1267 } 1268 public String toString() { 1269 synchronized (mutex) {return c.toString();} 1270 } 1271 // Override default methods in Collection 1272 @Override 1273 public void forEach(Consumer<? super E> consumer) { 1274 synchronized (mutex) {c.forEach(consumer);} 1275 } 1276 @Override 1277 public boolean removeIf(Predicate<? super E> filter) { 1278 synchronized (mutex) {return c.removeIf(filter);} 1279 } 1280 @Override 1281 public Spliterator<E> spliterator() { 1282 return c.spliterator(); // Must be manually synched by user! 1283 } 1284 @Override 1285 public Stream<E> stream() { 1286 return c.stream(); // Must be manually synched by user! 1287 } 1288 @Override 1289 public Stream<E> parallelStream() { 1290 return c.parallelStream(); // Must be manually synched by user! 1291 } 1292 private void writeObject(ObjectOutputStream s) throws IOException { 1293 synchronized (mutex) {s.defaultWriteObject();} 1294 } 1295 } 1296 1297 1298 // Dynamically typesafe collection wrappers 1299 1300 /** 1301 * Returns a dynamically typesafe view of the specified collection. 1302 * Any attempt to insert an element of the wrong type will result in an 1303 * immediate {@link ClassCastException}. Assuming a collection 1304 * contains no incorrectly typed elements prior to the time a 1305 * dynamically typesafe view is generated, and that all subsequent 1306 * access to the collection takes place through the view, it is 1307 * <i>guaranteed</i> that the collection cannot contain an incorrectly 1308 * typed element. 1309 * 1310 * <p>The generics mechanism in the language provides compile-time 1311 * (static) type checking, but it is possible to defeat this mechanism 1312 * with unchecked casts. Usually this is not a problem, as the compiler 1313 * issues warnings on all such unchecked operations. There are, however, 1314 * times when static type checking alone is not sufficient. For example, 1315 * suppose a collection is passed to a third-party library and it is 1316 * imperative that the library code not corrupt the collection by 1317 * inserting an element of the wrong type. 1318 * 1319 * <p>Another use of dynamically typesafe views is debugging. Suppose a 1320 * program fails with a {@code ClassCastException}, indicating that an 1321 * incorrectly typed element was put into a parameterized collection. 1322 * Unfortunately, the exception can occur at any time after the erroneous 1323 * element is inserted, so it typically provides little or no information 1324 * as to the real source of the problem. If the problem is reproducible, 1325 * one can quickly determine its source by temporarily modifying the 1326 * program to wrap the collection with a dynamically typesafe view. 1327 * For example, this declaration: 1328 * <pre> {@code 1329 * Collection<String> c = new HashSet<>(); 1330 * }</pre> 1331 * may be replaced temporarily by this one: 1332 * <pre> {@code 1333 * Collection<String> c = Collections.checkedCollection( 1334 * new HashSet<>(), String.class); 1335 * }</pre> 1336 * Running the program again will cause it to fail at the point where 1337 * an incorrectly typed element is inserted into the collection, clearly 1338 * identifying the source of the problem. Once the problem is fixed, the 1339 * modified declaration may be reverted back to the original. 1340 * 1341 * <p>The returned collection does <i>not</i> pass the hashCode and equals 1342 * operations through to the backing collection, but relies on 1343 * {@code Object}'s {@code equals} and {@code hashCode} methods. This 1344 * is necessary to preserve the contracts of these operations in the case 1345 * that the backing collection is a set or a list. 1346 * 1347 * <p>The returned collection will be serializable if the specified 1348 * collection is serializable. 1349 * 1350 * <p>Since {@code null} is considered to be a value of any reference 1351 * type, the returned collection permits insertion of null elements 1352 * whenever the backing collection does. 1353 * 1354 * @param <E> the class of the objects in the collection 1355 * @param c the collection for which a dynamically typesafe view is to be 1356 * returned 1357 * @param type the type of element that {@code c} is permitted to hold 1358 * @return a dynamically typesafe view of the specified collection 1359 * @since 1.5 1360 */ 1361 //返回指定 collection 的一个动态类型安全视图。用以检测元素类型是否正确。 1362 public static <E> Collection<E> checkedCollection(Collection<E> c, 1363 Class<E> type) { 1364 return new CheckedCollection<>(c, type); 1365 } 1366 1367 @SuppressWarnings("unchecked") 1368 static <T> T[] zeroLengthArray(Class<T> type) { 1369 return (T[]) Array.newInstance(type, 0); 1370 } 1371 1372 /** 1373 * @serial include 1374 */ 1375 static class CheckedCollection<E> implements Collection<E>, Serializable { 1376 private static final long serialVersionUID = 1578914078182001775L; 1377 1378 final Collection<E> c; 1379 final Class<E> type; 1380 1381 @SuppressWarnings("unchecked") 1382 E typeCheck(Object o) { 1383 if (o != null && !type.isInstance(o)) 1384 throw new ClassCastException(badElementMsg(o)); 1385 return (E) o; 1386 } 1387 1388 private String badElementMsg(Object o) { 1389 return "Attempt to insert " + o.getClass() + 1390 " element into collection with element type " + type; 1391 } 1392 1393 CheckedCollection(Collection<E> c, Class<E> type) { 1394 this.c = Objects.requireNonNull(c, "c"); 1395 this.type = Objects.requireNonNull(type, "type"); 1396 } 1397 1398 public int size() { return c.size(); } 1399 public boolean isEmpty() { return c.isEmpty(); } 1400 public boolean contains(Object o) { return c.contains(o); } 1401 public Object[] toArray() { return c.toArray(); } 1402 public <T> T[] toArray(T[] a) { return c.toArray(a); } 1403 public String toString() { return c.toString(); } 1404 public boolean remove(Object o) { return c.remove(o); } 1405 public void clear() { c.clear(); } 1406 1407 public boolean containsAll(Collection<?> coll) { 1408 return c.containsAll(coll); 1409 } 1410 public boolean removeAll(Collection<?> coll) { 1411 return c.removeAll(coll); 1412 } 1413 public boolean retainAll(Collection<?> coll) { 1414 return c.retainAll(coll); 1415 } 1416 1417 public Iterator<E> iterator() { 1418 // JDK-6363904 - unwrapped iterator could be typecast to 1419 // ListIterator with unsafe set() 1420 final Iterator<E> it = c.iterator(); 1421 return new Iterator<E>() { 1422 public boolean hasNext() { return it.hasNext(); } 1423 public E next() { return it.next(); } 1424 public void remove() { it.remove(); }}; 1425 } 1426 1427 public boolean add(E e) { return c.add(typeCheck(e)); } 1428 1429 private E[] zeroLengthElementArray; // Lazily initialized 1430 1431 private E[] zeroLengthElementArray() { 1432 return zeroLengthElementArray != null ? zeroLengthElementArray : 1433 (zeroLengthElementArray = zeroLengthArray(type)); 1434 } 1435 1436 @SuppressWarnings("unchecked") 1437 Collection<E> checkedCopyOf(Collection<? extends E> coll) { 1438 Object[] a; 1439 try { 1440 E[] z = zeroLengthElementArray(); 1441 a = coll.toArray(z); 1442 // Defend against coll violating the toArray contract 1443 if (a.getClass() != z.getClass()) 1444 a = Arrays.copyOf(a, a.length, z.getClass()); 1445 } catch (ArrayStoreException ignore) { 1446 // To get better and consistent diagnostics, 1447 // we call typeCheck explicitly on each element. 1448 // We call clone() to defend against coll retaining a 1449 // reference to the returned array and storing a bad 1450 // element into it after it has been type checked. 1451 a = coll.toArray().clone(); 1452 for (Object o : a) 1453 typeCheck(o); 1454 } 1455 // A slight abuse of the type system, but safe here. 1456 return (Collection<E>) Arrays.asList(a); 1457 } 1458 1459 public boolean addAll(Collection<? extends E> coll) { 1460 // Doing things this way insulates us from concurrent changes 1461 // in the contents of coll and provides all-or-nothing 1462 // semantics (which we wouldn't get if we type-checked each 1463 // element as we added it) 1464 return c.addAll(checkedCopyOf(coll)); 1465 } 1466 1467 // Override default methods in Collection 1468 @Override 1469 public void forEach(Consumer<? super E> action) {c.forEach(action);} 1470 @Override 1471 public boolean removeIf(Predicate<? super E> filter) { 1472 return c.removeIf(filter); 1473 } 1474 @Override 1475 public Spliterator<E> spliterator() {return c.spliterator();} 1476 @Override 1477 public Stream<E> stream() {return c.stream();} 1478 @Override 1479 public Stream<E> parallelStream() {return c.parallelStream();} 1480 } 1481 1482 1483 1484 1485 1486 1487 1488 /** 1489 * Returns an immutable list containing only the specified object. 1490 * The returned list is serializable. 1491 * 1492 * @param <T> the class of the objects in the list 1493 * @param o the sole object to be stored in the returned list. 1494 * @return an immutable list containing only the specified object. 1495 * @since 1.3 1496 */ 1497 //返回一个只包含指定对象的不可变列表。返回的列表是可序列化的。 1498 public static <T> List<T> singletonList(T o) { 1499 return new SingletonList<>(o); 1500 } 1501 1502 /** 1503 * @serial include 1504 */ 1505 private static class SingletonList<E> 1506 extends AbstractList<E> 1507 implements RandomAccess, Serializable { 1508 1509 private static final long serialVersionUID = 3093736618740652951L; 1510 1511 private final E element; 1512 1513 SingletonList(E obj) {element = obj;} 1514 1515 public Iterator<E> iterator() { 1516 return singletonIterator(element); 1517 } 1518 1519 public int size() {return 1;} 1520 1521 public boolean contains(Object obj) {return eq(obj, element);} 1522 1523 public E get(int index) { 1524 if (index != 0) 1525 throw new IndexOutOfBoundsException("Index: "+index+", Size: 1"); 1526 return element; 1527 } 1528 1529 // Override default methods for Collection 1530 @Override 1531 public void forEach(Consumer<? super E> action) { 1532 action.accept(element); 1533 } 1534 @Override 1535 public boolean removeIf(Predicate<? super E> filter) { 1536 throw new UnsupportedOperationException(); 1537 } 1538 @Override 1539 public void replaceAll(UnaryOperator<E> operator) { 1540 throw new UnsupportedOperationException(); 1541 } 1542 @Override 1543 public void sort(Comparator<? super E> c) { 1544 } 1545 @Override 1546 public Spliterator<E> spliterator() { 1547 return singletonSpliterator(element); 1548 } 1549 } 1550 1551 1552 // Miscellaneous 1553 1554 /** 1555 * Returns an immutable list consisting of <tt>n</tt> copies of the 1556 * specified object. The newly allocated data object is tiny (it contains 1557 * a single reference to the data object). This method is useful in 1558 * combination with the <tt>List.addAll</tt> method to grow lists. 1559 * The returned list is serializable. 1560 * 1561 * @param <T> the class of the object to copy and of the objects 1562 * in the returned list. 1563 * @param n the number of elements in the returned list. 1564 * @param o the element to appear repeatedly in the returned list. 1565 * @return an immutable list consisting of <tt>n</tt> copies of the 1566 * specified object. 1567 * @throws IllegalArgumentException if {@code n < 0} 1568 * @see List#addAll(Collection) 1569 * @see List#addAll(int, Collection) 1570 */ 1571 //返回由指定对象的 n 个副本组成的不可变列表。 1572 //新分配的数据对象非常小(它只包含一个对该数据对象的引用)。在通过与 List.addAll 方法组合来增大列表时,此方法很有用 1573 public static <T> List<T> nCopies(int n, T o) { 1574 if (n < 0) 1575 throw new IllegalArgumentException("List length = " + n); 1576 return new CopiesList<>(n, o); 1577 } 1578 1579 /** 1580 * @serial include 1581 */ 1582 private static class CopiesList<E> 1583 extends AbstractList<E> 1584 implements RandomAccess, Serializable 1585 { 1586 private static final long serialVersionUID = 2739099268398711800L; 1587 1588 final int n; 1589 final E element; 1590 1591 CopiesList(int n, E e) { 1592 assert n >= 0; 1593 this.n = n; 1594 element = e; 1595 } 1596 1597 public int size() { 1598 return n; 1599 } 1600 1601 public boolean contains(Object obj) { 1602 return n != 0 && eq(obj, element); 1603 } 1604 1605 public int indexOf(Object o) { 1606 return contains(o) ? 0 : -1; 1607 } 1608 1609 public int lastIndexOf(Object o) { 1610 return contains(o) ? n - 1 : -1; 1611 } 1612 1613 public E get(int index) { 1614 if (index < 0 || index >= n) 1615 throw new IndexOutOfBoundsException("Index: "+index+ 1616 ", Size: "+n); 1617 return element; 1618 } 1619 1620 public Object[] toArray() { 1621 final Object[] a = new Object[n]; 1622 if (element != null) 1623 Arrays.fill(a, 0, n, element); 1624 return a; 1625 } 1626 1627 @SuppressWarnings("unchecked") 1628 public <T> T[] toArray(T[] a) { 1629 final int n = this.n; 1630 if (a.length < n) { 1631 a = (T[])java.lang.reflect.Array 1632 .newInstance(a.getClass().getComponentType(), n); 1633 if (element != null) 1634 Arrays.fill(a, 0, n, element); 1635 } else { 1636 Arrays.fill(a, 0, n, element); 1637 if (a.length > n) 1638 a[n] = null; 1639 } 1640 return a; 1641 } 1642 1643 public List<E> subList(int fromIndex, int toIndex) { 1644 if (fromIndex < 0) 1645 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); 1646 if (toIndex > n) 1647 throw new IndexOutOfBoundsException("toIndex = " + toIndex); 1648 if (fromIndex > toIndex) 1649 throw new IllegalArgumentException("fromIndex(" + fromIndex + 1650 ") > toIndex(" + toIndex + ")"); 1651 return new CopiesList<>(toIndex - fromIndex, element); 1652 } 1653 1654 // Override default methods in Collection 1655 @Override 1656 public Stream<E> stream() { 1657 return IntStream.range(0, n).mapToObj(i -> element); 1658 } 1659 1660 @Override 1661 public Stream<E> parallelStream() { 1662 return IntStream.range(0, n).parallel().mapToObj(i -> element); 1663 } 1664 1665 @Override 1666 public Spliterator<E> spliterator() { 1667 return stream().spliterator(); 1668 } 1669 } 1670 1671 /** 1672 * Returns a comparator that imposes the reverse of the <em>natural 1673 * ordering</em> on a collection of objects that implement the 1674 * {@code Comparable} interface. (The natural ordering is the ordering 1675 * imposed by the objects' own {@code compareTo} method.) This enables a 1676 * simple idiom for sorting (or maintaining) collections (or arrays) of 1677 * objects that implement the {@code Comparable} interface in 1678 * reverse-natural-order. For example, suppose {@code a} is an array of 1679 * strings. Then: <pre> 1680 * Arrays.sort(a, Collections.reverseOrder()); 1681 * </pre> sorts the array in reverse-lexicographic (alphabetical) order.<p> 1682 * 1683 * The returned comparator is serializable. 1684 * 1685 * @param <T> the class of the objects compared by the comparator 1686 * @return A comparator that imposes the reverse of the <i>natural 1687 * ordering</i> on a collection of objects that implement 1688 * the <tt>Comparable</tt> interface. 1689 * @see Comparable 1690 */ 1691 //返回一个比较器,它强行逆转实现了 Comparable 接口的对象 collection 的自然顺序。 1692 @SuppressWarnings("unchecked") 1693 public static <T> Comparator<T> reverseOrder() { 1694 return (Comparator<T>) ReverseComparator.REVERSE_ORDER; 1695 } 1696 1697 /** 1698 * @serial include 1699 */ 1700 private static class ReverseComparator 1701 implements Comparator<Comparable<Object>>, Serializable { 1702 1703 private static final long serialVersionUID = 7207038068494060240L; 1704 1705 static final ReverseComparator REVERSE_ORDER 1706 = new ReverseComparator(); 1707 1708 public int compare(Comparable<Object> c1, Comparable<Object> c2) { 1709 return c2.compareTo(c1); 1710 } 1711 1712 private Object readResolve() { return Collections.reverseOrder(); } 1713 1714 @Override 1715 public Comparator<Comparable<Object>> reversed() { 1716 return Comparator.naturalOrder(); 1717 } 1718 } 1719 1720 /** 1721 * Returns a comparator that imposes the reverse ordering of the specified 1722 * comparator. If the specified comparator is {@code null}, this method is 1723 * equivalent to {@link #reverseOrder()} (in other words, it returns a 1724 * comparator that imposes the reverse of the <em>natural ordering</em> on 1725 * a collection of objects that implement the Comparable interface). 1726 * 1727 * <p>The returned comparator is serializable (assuming the specified 1728 * comparator is also serializable or {@code null}). 1729 * 1730 * @param <T> the class of the objects compared by the comparator 1731 * @param cmp a comparator who's ordering is to be reversed by the returned 1732 * comparator or {@code null} 1733 * @return A comparator that imposes the reverse ordering of the 1734 * specified comparator. 1735 * @since 1.5 1736 */ 1737 //返回一个比较器,它强行逆转指定比较器的顺序。 1738 public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) { 1739 if (cmp == null) 1740 return reverseOrder(); 1741 1742 if (cmp instanceof ReverseComparator2) 1743 return ((ReverseComparator2<T>)cmp).cmp; 1744 1745 return new ReverseComparator2<>(cmp); 1746 } 1747 1748 /** 1749 * @serial include 1750 */ 1751 private static class ReverseComparator2<T> implements Comparator<T>, 1752 Serializable 1753 { 1754 private static final long serialVersionUID = 4374092139857L; 1755 1756 /** 1757 * The comparator specified in the static factory. This will never 1758 * be null, as the static factory returns a ReverseComparator 1759 * instance if its argument is null. 1760 * 1761 * @serial 1762 */ 1763 final Comparator<T> cmp; 1764 1765 ReverseComparator2(Comparator<T> cmp) { 1766 assert cmp != null; 1767 this.cmp = cmp; 1768 } 1769 1770 public int compare(T t1, T t2) { 1771 return cmp.compare(t2, t1); 1772 } 1773 1774 public boolean equals(Object o) { 1775 return (o == this) || 1776 (o instanceof ReverseComparator2 && 1777 cmp.equals(((ReverseComparator2)o).cmp)); 1778 } 1779 1780 public int hashCode() { 1781 return cmp.hashCode() ^ Integer.MIN_VALUE; 1782 } 1783 1784 @Override 1785 public Comparator<T> reversed() { 1786 return cmp; 1787 } 1788 } 1789 1790 1791 1792 /** 1793 * Returns an array list containing the elements returned by the 1794 * specified enumeration in the order they are returned by the 1795 * enumeration. This method provides interoperability between 1796 * legacy APIs that return enumerations and new APIs that require 1797 * collections. 1798 * 1799 * @param <T> the class of the objects returned by the enumeration 1800 * @param e enumeration providing elements for the returned 1801 * array list 1802 * @return an array list containing the elements returned 1803 * by the specified enumeration. 1804 * @since 1.4 1805 * @see Enumeration 1806 * @see ArrayList 1807 */ 1808 public static <T> ArrayList<T> list(Enumeration<T> e) { 1809 ArrayList<T> l = new ArrayList<>(); 1810 while (e.hasMoreElements()) 1811 l.add(e.nextElement()); 1812 return l; 1813 } 1814 1815 /** 1816 * Returns the number of elements in the specified collection equal to the 1817 * specified object. More formally, returns the number of elements 1818 * <tt>e</tt> in the collection such that 1819 * <tt>(o == null ? e == null : o.equals(e))</tt>. 1820 * 1821 * @param c the collection in which to determine the frequency 1822 * of <tt>o</tt> 1823 * @param o the object whose frequency is to be determined 1824 * @return the number of elements in {@code c} equal to {@code o} 1825 * @throws NullPointerException if <tt>c</tt> is null 1826 * @since 1.5 1827 */ 1828 //返回指定 collection 中等于指定对象的元素数。 1829 //更确切地讲,返回 collection 中满足 (o == null ? e == null : o.equals(e)) 的 e 元素的数量。 1830 public static int frequency(Collection<?> c, Object o) { 1831 int result = 0; 1832 if (o == null) { 1833 for (Object e : c) 1834 if (e == null) 1835 result++; 1836 } else { 1837 for (Object e : c) 1838 if (o.equals(e)) 1839 result++; 1840 } 1841 return result; 1842 } 1843 1844 /** 1845 * Returns {@code true} if the two specified collections have no 1846 * elements in common. 1847 * 1848 * <p>Care must be exercised if this method is used on collections that 1849 * do not comply with the general contract for {@code Collection}. 1850 * Implementations may elect to iterate over either collection and test 1851 * for containment in the other collection (or to perform any equivalent 1852 * computation). If either collection uses a nonstandard equality test 1853 * (as does a {@link SortedSet} whose ordering is not <em>compatible with 1854 * equals</em>, or the key set of an {@link IdentityHashMap}), both 1855 * collections must use the same nonstandard equality test, or the 1856 * result of this method is undefined. 1857 * 1858 * <p>Care must also be exercised when using collections that have 1859 * restrictions on the elements that they may contain. Collection 1860 * implementations are allowed to throw exceptions for any operation 1861 * involving elements they deem ineligible. For absolute safety the 1862 * specified collections should contain only elements which are 1863 * eligible elements for both collections. 1864 * 1865 * <p>Note that it is permissible to pass the same collection in both 1866 * parameters, in which case the method will return {@code true} if and 1867 * only if the collection is empty. 1868 * 1869 * @param c1 a collection 1870 * @param c2 a collection 1871 * @return {@code true} if the two specified collections have no 1872 * elements in common. 1873 * @throws NullPointerException if either collection is {@code null}. 1874 * @throws NullPointerException if one collection contains a {@code null} 1875 * element and {@code null} is not an eligible element for the other collection. 1876 * (<a href="Collection.html#optional-restrictions">optional</a>) 1877 * @throws ClassCastException if one collection contains an element that is 1878 * of a type which is ineligible for the other collection. 1879 * (<a href="Collection.html#optional-restrictions">optional</a>) 1880 * @since 1.5 1881 */ 1882 1883 //如果两个指定 collection 中没有相同的元素,则返回 true。 1884 //如果将此方法用在不符合 Collection 常规协定的 collection 上,则必须小心。 1885 //实现可以在任一 collection 上进行迭代,测试元素是否包含在另一个 collection 中(或执行任何等效的计算)。 1886 //如果任一 collection 使用了一个非标准的相等性测试(比如顺序不是与 equals 一致的 SortedSet, 1887 //或者 IdentityHashMap 的键集),则两个 collection 1888 //都必须使用相同的非标准相等性测试,否则此方法的结果是不确定的。 1889 //注意,允许在两个参数中传递相同的 collection,在这种情况下,当且仅当 collection 为空时此方法返回 true。 1890 public static boolean disjoint(Collection<?> c1, Collection<?> c2) { 1891 // The collection to be used for contains(). Preference is given to 1892 // the collection who's contains() has lower O() complexity. 1893 Collection<?> contains = c2; 1894 // The collection to be iterated. If the collections' contains() impl 1895 // are of different O() complexity, the collection with slower 1896 // contains() will be used for iteration. For collections who's 1897 // contains() are of the same complexity then best performance is 1898 // achieved by iterating the smaller collection. 1899 Collection<?> iterate = c1; 1900 1901 // Performance optimization cases. The heuristics: 1902 // 1. Generally iterate over c1. 1903 // 2. If c1 is a Set then iterate over c2. 1904 // 3. If either collection is empty then result is always true. 1905 // 4. Iterate over the smaller Collection. 1906 if (c1 instanceof Set) { 1907 // Use c1 for contains as a Set's contains() is expected to perform 1908 // better than O(N/2) 1909 iterate = c2; 1910 contains = c1; 1911 } else if (!(c2 instanceof Set)) { 1912 // Both are mere Collections. Iterate over smaller collection. 1913 // Example: If c1 contains 3 elements and c2 contains 50 elements and 1914 // assuming contains() requires ceiling(N/2) comparisons then 1915 // checking for all c1 elements in c2 would require 75 comparisons 1916 // (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring 1917 // 100 comparisons (50 * ceiling(3/2)). 1918 int c1size = c1.size(); 1919 int c2size = c2.size(); 1920 if (c1size == 0 || c2size == 0) { 1921 // At least one collection is empty. Nothing will match. 1922 return true; 1923 } 1924 1925 if (c1size > c2size) { 1926 iterate = c2; 1927 contains = c1; 1928 } 1929 } 1930 1931 for (Object e : iterate) { 1932 if (contains.contains(e)) { 1933 // Found a common element. Collections are not disjoint. 1934 return false; 1935 } 1936 } 1937 1938 // No common elements were found. 1939 return true; 1940 } 1941 1942 1943 1944 /** 1945 * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo) 1946 * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>, 1947 * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This 1948 * view can be useful when you would like to use a method 1949 * requiring a <tt>Queue</tt> but you need Lifo ordering. 1950 * 1951 * <p>Each method invocation on the queue returned by this method 1952 * results in exactly one method invocation on the backing deque, with 1953 * one exception. The {@link Queue#addAll addAll} method is 1954 * implemented as a sequence of {@link Deque#addFirst addFirst} 1955 * invocations on the backing deque. 1956 * 1957 * @param <T> the class of the objects in the deque 1958 * @param deque the deque 1959 * @return the queue 1960 * @since 1.6 1961 */ 1962 //以后进先出 (Lifo) Queue 的形式返回某个 Deque 的视图。 1963 //方法 add 被映射到 push,remove 被映射到 pop 等等。 1964 //在希望使用某一方法获取一个 Queue 并且需要它具有 Lifo 顺序时,此方法很有用。 1965 //每次在此方法返回的队列上调用方法都将导致在底层实现队列上调用该方法一次, 1966 并伴随一个异常。addAll 方法是作为底层实现队列上的 addFirst 调用序列实现的。 1967 public static <T> Queue<T> asLifoQueue(Deque<T> deque) { 1968 return new AsLIFOQueue<>(deque); 1969 } 1970 1971 /** 1972 * @serial include 1973 */ 1974 static class AsLIFOQueue<E> extends AbstractQueue<E> 1975 implements Queue<E>, Serializable { 1976 private static final long serialVersionUID = 1802017725587941708L; 1977 private final Deque<E> q; 1978 AsLIFOQueue(Deque<E> q) { this.q = q; } 1979 public boolean add(E e) { q.addFirst(e); return true; } 1980 public boolean offer(E e) { return q.offerFirst(e); } 1981 public E poll() { return q.pollFirst(); } 1982 public E remove() { return q.removeFirst(); } 1983 public E peek() { return q.peekFirst(); } 1984 public E element() { return q.getFirst(); } 1985 public void clear() { q.clear(); } 1986 public int size() { return q.size(); } 1987 public boolean isEmpty() { return q.isEmpty(); } 1988 public boolean contains(Object o) { return q.contains(o); } 1989 public boolean remove(Object o) { return q.remove(o); } 1990 public Iterator<E> iterator() { return q.iterator(); } 1991 public Object[] toArray() { return q.toArray(); } 1992 public <T> T[] toArray(T[] a) { return q.toArray(a); } 1993 public String toString() { return q.toString(); } 1994 public boolean containsAll(Collection<?> c) {return q.containsAll(c);} 1995 public boolean removeAll(Collection<?> c) {return q.removeAll(c);} 1996 public boolean retainAll(Collection<?> c) {return q.retainAll(c);} 1997 // We use inherited addAll; forwarding addAll would be wrong 1998 1999 // Override default methods in Collection 2000 @Override 2001 public void forEach(Consumer<? super E> action) {q.forEach(action);} 2002 @Override 2003 public boolean removeIf(Predicate<? super E> filter) { 2004 return q.removeIf(filter); 2005 } 2006 @Override 2007 public Spliterator<E> spliterator() {return q.spliterator();} 2008 @Override 2009 public Stream<E> stream() {return q.stream();} 2010 @Override 2011 public Stream<E> parallelStream() {return q.parallelStream();} 2012 } 2013 }