java1.8的collections_JDK1.8源码Collections

1 public classCollections {2 //Suppresses default constructor, ensuring non-instantiability.

3 privateCollections() {4 }5

6 //Algorithms

7

8 /*

9 * Tuning parameters for algorithms - Many of the List algorithms have10 * two implementations, one of which is appropriate for RandomAccess11 * lists, the other for "sequential." Often, the random access variant12 * yields better performance on small sequential access lists. The13 * tuning parameters below determine the cutoff point for what constitutes14 * a "small" sequential access list for each algorithm. The values below15 * were empirically determined to work well for LinkedList. Hopefully16 * they should be reasonable for other sequential access List17 * implementations. Those doing performance work on this code would18 * 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 which20 * 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 the33 * {@linkplainComparable natural ordering} of its elements.34 * All elements in the list must implement the {@linkComparable}35 * interface. Furthermore, all elements in the list must be36 * mutually comparable (that is, {@codee1.compareTo(e2)}37 * must not throw a {@codeClassCastException} for any elements38 * {@codee1} and {@codee2} in the list).39 *40 *

This sort is guaranteed to be stable: equal elements will41 * not be reordered as a result of the sort.42 *43 *

The specified list must be modifiable, but need not be resizable.44 *45 * @implNote46 * This implementation defers to the {@linkList#sort(Comparator)}47 * method using the specified list and a {@codenull} comparator.48 *49 *@param the class of the objects in the list50 *@paramlist the list to be sorted.51 *@throwsClassCastException if the list contains elements that are not52 * mutually comparable (for example, strings and integers).53 *@throwsUnsupportedOperationException if the specified list's54 * list-iterator does not support the {@codeset} operation.55 *@throwsIllegalArgumentException (optional) if the implementation56 * detects that the natural ordering of the list elements is57 * found to violate the {@linkComparable} contract58 *@seeList#sort(Comparator)59 */

60 //根据元素的自然顺序 对指定列表按升序进行排序。列表中的所有元素都必须实现 Comparable 接口

61 @SuppressWarnings("unchecked")62 public static > void sort(Listlist) {63 list.sort(null);64 }65

66 /**

67 * Sorts the specified list according to the order induced by the68 * specified comparator. All elements in the list must be mutually69 * comparable using the specified comparator (that is,70 * {@codec.compare(e1, e2)} must not throw a {@codeClassCastException}71 * for any elements {@codee1} and {@codee2} in the list).72 *73 *

This sort is guaranteed to be stable: equal elements will74 * not be reordered as a result of the sort.75 *76 *

The specified list must be modifiable, but need not be resizable.77 *78 * @implNote79 * This implementation defers to the {@linkList#sort(Comparator)}80 * method using the specified list and comparator.81 *82 *@param the class of the objects in the list83 *@paramlist the list to be sorted.84 *@paramc the comparator to determine the order of the list. A85 * {@codenull} value indicates that the elements' natural86 * ordering should be used.87 *@throwsClassCastException if the list contains elements that are not88 * mutually comparable using the specified comparator.89 *@throwsUnsupportedOperationException if the specified list's90 * list-iterator does not support the {@codeset} operation.91 *@throwsIllegalArgumentException (optional) if the comparator is92 * found to violate the {@linkComparator} contract93 *@seeList#sort(Comparator)94 */

95 //根据指定比较器产生的顺序对指定列表进行排序。

96 @SuppressWarnings({"unchecked", "rawtypes"})97 public static void sort(List list, Comparator super T>c) {98 list.sort(c);99 }100

101

102 /**

103 * Searches the specified list for the specified object using the binary104 * search algorithm. The list must be sorted into ascending order105 * according to the {@linkplainComparable natural ordering} of its106 * elements (as by the {@link#sort(List)} method) prior to making this107 * call. If it is not sorted, the results are undefined. If the list108 * contains multiple elements equal to the specified object, there is no109 * guarantee which one will be found.110 *111 *

This method runs in log(n) time for a "random access" list (which112 * provides near-constant-time positional access). If the specified list113 * does not implement the {@linkRandomAccess} interface and is large,114 * this method will do an iterator-based binary search that performs115 * O(n) link traversals and O(log n) element comparisons.116 *117 *@param the class of the objects in the list118 *@paramlist the list to be searched.119 *@paramkey the key to be searched for.120 *@returnthe index of the search key, if it is contained in the list;121 * otherwise, (-(insertion point) - 1). The122 * insertion point is defined as the point at which the123 * key would be inserted into the list: the index of the first124 * element greater than the key, or list.size() if all125 * elements in the list are less than the specified key. Note126 * that this guarantees that the return value will be >= 0 if127 * and only if the key is found.128 *@throwsClassCastException if the list contains elements that are not129 * mutually comparable (for example, strings and130 * integers), or the search key is not mutually comparable131 * with the elements of the list.132 */

133 //使用二分搜索法搜索指定列表,以获得指定对象。在进行此调用之前,必须根据列表元素的自然顺序对列表进行升序排序(通过 sort(List)//方法)。如果没有对列表进行排序,则结果是不确定的。如果列表包含多个等于指定对象的元素,则无法保证找到的是哪一个。

134 public static

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()

139 returnCollections.indexedBinarySearch(list, key);140 else

141 returnCollections.iteratorBinarySearch(list, key);142 }143

144 private static

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

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 specified188 * list listIterator.189 */

190 private static T get(ListIterator extends T> i, intindex) {191 T obj = null;192 int pos =i.nextIndex();193 if (pos <=index) {194 do{195 obj =i.next();196 } while (pos++ index);201 }202 returnobj;203 }204

205 /**

206 * Searches the specified list for the specified object using the binary207 * search algorithm. The list must be sorted into ascending order208 * according to the specified comparator (as by the209 * {@link#sort(List, Comparator) sort(List, Comparator)}210 * method), prior to making this call. If it is211 * not sorted, the results are undefined. If the list contains multiple212 * elements equal to the specified object, there is no guarantee which one213 * will be found.214 *215 *

This method runs in log(n) time for a "random access" list (which216 * provides near-constant-time positional access). If the specified list217 * does not implement the {@linkRandomAccess} interface and is large,218 * this method will do an iterator-based binary search that performs219 * O(n) link traversals and O(log n) element comparisons.220 *221 *@param the class of the objects in the list222 *@paramlist the list to be searched.223 *@paramkey the key to be searched for.224 *@paramc the comparator by which the list is ordered.225 * A null value indicates that the elements'226 * {@linkplainComparable natural ordering} should be used.227 *@returnthe index of the search key, if it is contained in the list;228 * otherwise, (-(insertion point) - 1). The229 * insertion point is defined as the point at which the230 * key would be inserted into the list: the index of the first231 * element greater than the key, or list.size() if all232 * elements in the list are less than the specified key. Note233 * that this guarantees that the return value will be >= 0 if234 * and only if the key is found.235 *@throwsClassCastException if the list contains elements that are not236 * mutually comparable using the specified comparator,237 * or the search key is not mutually comparable with the238 * elements of the list using this comparator.239 */

240 //使用二分搜索法搜索指定列表,以获得指定对象。在进行此调用之前,必须根据指定的比较器对列表进行升序排序(通过 sort(List, Comparator)//方法)。如果没有对列表进行排序,则结果是不确定的。如果列表包含多个等于指定对象的元素,则无法保证找到的是哪一个。

241 @SuppressWarnings("unchecked")242 public static 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()

249 returnCollections.iteratorBinarySearch(list, key, c);250 }251

252 private static 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 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.

293 *294 * This method runs in linear time.295 *296 *@paramlist the list whose elements are to be reversed.297 *@throwsUnsupportedOperationException if the specified list or298 * its list-iterator does not support the set 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 instanceofRandomAccess) {305 for (int i=0, mid=size>>1, j=size-1; i

311 ListIterator fwd =list.lis tIterator();312 ListIterator rev =list.listIterator(size);313 for (int i=0, mid=list.size()>>1; i

321 /**

322 * Randomly permutes the specified list using a default source of323 * randomness. All permutations occur with approximately equal324 * likelihood.325 *326 *

The hedge "approximately" is used in the foregoing description because327 * default source of randomness is only approximately an unbiased source328 * of independently chosen bits. If it were a perfect source of randomly329 * chosen bits, then the algorithm would choose permutations with perfect330 * uniformity.331 *332 *

This implementation traverses the list backwards, from the last333 * element up to the second, repeatedly swapping a randomly selected element334 * into the "current position". Elements are randomly selected from the335 * portion of the list that runs from the first element to the current336 * position, inclusive.337 *338 *

This method runs in linear time. If the specified list does not339 * implement the {@linkRandomAccess} interface and is large, this340 * implementation dumps the specified list into an array before shuffling341 * it, and dumps the shuffled array back into the list. This avoids the342 * quadratic behavior that would result from shuffling a "sequential343 * access" list in place.344 *345 *@paramlist the list to be shuffled.346 *@throwsUnsupportedOperationException if the specified list or347 * its list-iterator does not support the set 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 staticRandom r;362

363 /**

364 * Randomly permute the specified list using the specified source of365 * randomness. All permutations occur with equal likelihood366 * assuming that the source of randomness is fair.

367 *368 * This implementation traverses the list backwards, from the last element369 * up to the second, repeatedly swapping a randomly selected element into370 * the "current position". Elements are randomly selected from the371 * portion of the list that runs from the first element to the current372 * position, inclusive.

373 *374 * This method runs in linear time. If the specified list does not375 * implement the {@linkRandomAccess} interface and is large, this376 * implementation dumps the specified list into an array before shuffling377 * it, and dumps the shuffled array back into the list. This avoids the378 * quadratic behavior that would result from shuffling a "sequential379 * access" list in place.380 *381 *@paramlist the list to be shuffled.382 *@paramrnd the source of randomness to use to shuffle the list.383 *@throwsUnsupportedOperationException if the specified list or its384 * list-iterator does not support the set 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 instanceofRandomAccess) {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 list402 //instead of using a raw type here, it's possible to capture403 //the wildcard but it will require a call to a supplementary404 //private method

405 ListIterator it =list.listIterator();406 for (int i=0; i

413 /**

414 * Swaps the elements at the specified positions in the specified list.415 * (If the specified positions are equal, invoking this method leaves416 * the list unchanged.)417 *418 *@paramlist The list in which to swap elements.419 *@parami the index of one element to be swapped.420 *@paramj the index of the other element to be swapped.421 *@throwsIndexOutOfBoundsException if either i or j422 * is out of range (i < 0 || i >= list.size()423 * || j < 0 || j >= list.size()).424 *@since1.4425 */

426 //在指定列表的指定位置处交换元素

427 @SuppressWarnings({"rawtypes", "unchecked"})428 public static void swap(List> list, int i, intj) {429 //instead of using a raw type here, it's possible to capture430 //the wildcard but it will require a call to a supplementary431 //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, intj) {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 specified447 * element.

448 *449 * This method runs in linear time.450 *451 *@param the class of the objects in the list452 *@paramlist the list to be filled with the specified element.453 *@paramobj The element with which to fill the specified list.454 *@throwsUnsupportedOperationException if the specified list or its455 * list-iterator does not support the set operation.456 */

457 //使用指定元素替换指定列表中的所有元素。

458 public static void fill(List super T>list, T obj) {459 int size =list.size();460

461 if (size < FILL_THRESHOLD || list instanceofRandomAccess) {462 for (int i=0; i itr =list.listIterator();466 for (int i=0; i

473 /**

474 * Copies all of the elements from one list into another. After the475 * operation, the index of each copied element in the destination list476 * will be identical to its index in the source list. The destination477 * list must be at least as long as the source list. If it is longer, the478 * remaining elements in the destination list are unaffected.

479 *480 * This method runs in linear time.481 *482 *@param the class of the objects in the lists483 *@paramdest The destination list.484 *@paramsrc The source list.485 *@throwsIndexOutOfBoundsException if the destination list is too small486 * to contain the entire source List.487 *@throwsUnsupportedOperationException if the destination list's488 * list-iterator does not support the set operation.489 */

490 //将所有元素从一个列表复制到另一个列表491 //目标列表的长度至少必须等于源列表。

492 public static 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 instanceofRandomAccess)) {499 for (int i=0; i di=dest.listIterator();503 ListIterator extends T> si=src.listIterator();504 for (int i=0; i

511 /**

512 * Returns the minimum element of the given collection, according to the513 * natural ordering of its elements. All elements in the514 * collection must implement the Comparable interface.515 * Furthermore, all elements in the collection must be mutually516 * comparable (that is, e1.compareTo(e2) must not throw a517 * ClassCastException for any elements e1 and518 * e2 in the collection).

519 *520 * This method iterates over the entire collection, hence it requires521 * time proportional to the size of the collection.522 *523 *@param the class of the objects in the collection524 *@paramcoll the collection whose minimum element is to be determined.525 *@returnthe minimum element of the given collection, according526 * to the natural ordering of its elements.527 *@throwsClassCastException if the collection contains elements that are528 * not mutually comparable (for example, strings and529 * integers).530 *@throwsNoSuchElementException if the collection is empty.531 *@seeComparable532 */

533 //根据元素的自然顺序 返回给定 collection 的最小元素。collection 中的所有元素都必须实现 Comparable 接口。

534 public static > 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 returncandidate;544 }545

546 /**

547 * Returns the minimum element of the given collection, according to the548 * order induced by the specified comparator. All elements in the549 * collection must be mutually comparable by the specified550 * comparator (that is, comp.compare(e1, e2) must not throw a551 * ClassCastException for any elements e1 and552 * e2 in the collection).

553 *554 * This method iterates over the entire collection, hence it requires555 * time proportional to the size of the collection.556 *557 *@param the class of the objects in the collection558 *@paramcoll the collection whose minimum element is to be determined.559 *@paramcomp the comparator with which to determine the minimum element.560 * A null value indicates that the elements' natural561 * ordering should be used.562 *@returnthe minimum element of the given collection, according563 * to the specified comparator.564 *@throwsClassCastException if the collection contains elements that are565 * not mutually comparable using the specified comparator.566 *@throwsNoSuchElementException if the collection is empty.567 *@seeComparable568 */

569 //根据指定比较器产生的顺序,返回给定 collection 的最小元素。同min

570 @SuppressWarnings({"unchecked", "rawtypes"})571 public static 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 returncandidate;584 }585

586 /**

587 * Returns the maximum element of the given collection, according to the588 * natural ordering of its elements. All elements in the589 * collection must implement the Comparable interface.590 * Furthermore, all elements in the collection must be mutually591 * comparable (that is, e1.compareTo(e2) must not throw a592 * ClassCastException for any elements e1 and593 * e2 in the collection).

594 *595 * This method iterates over the entire collection, hence it requires596 * time proportional to the size of the collection.597 *598 *@param the class of the objects in the collection599 *@paramcoll the collection whose maximum element is to be determined.600 *@returnthe maximum element of the given collection, according601 * to the natural ordering of its elements.602 *@throwsClassCastException if the collection contains elements that are603 * not mutually comparable (for example, strings and604 * integers).605 *@throwsNoSuchElementException if the collection is empty.606 *@seeComparable607 */

608 //根据元素的自然顺序,返回给定 collection 的最大元素。同min

609 public static > 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 returncandidate;619 }620

621 /**

622 * Returns the maximum element of the given collection, according to the623 * order induced by the specified comparator. All elements in the624 * collection must be mutually comparable by the specified625 * comparator (that is, comp.compare(e1, e2) must not throw a626 * ClassCastException for any elements e1 and627 * e2 in the collection).

628 *629 * This method iterates over the entire collection, hence it requires630 * time proportional to the size of the collection.631 *632 *@param the class of the objects in the collection633 *@paramcoll the collection whose maximum element is to be determined.634 *@paramcomp the comparator with which to determine the maximum element.635 * A null value indicates that the elements' natural636 * ordering should be used.637 *@returnthe maximum element of the given collection, according638 * to the specified comparator.639 *@throwsClassCastException if the collection contains elements that are640 * not mutually comparable using the specified comparator.641 *@throwsNoSuchElementException if the collection is empty.642 *@seeComparable643 */

644 //根据指定比较器产生的顺序,返回给定 collection 的最大元素。同min

645 @SuppressWarnings({"unchecked", "rawtypes"})646 public static 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 returncandidate;659 }660

661 /**

662 * Rotates the elements in the specified list by the specified distance.663 * After calling this method, the element at index i will be664 * the element previously at index (i - distance) mod665 * list.size(), for all values of i between 0666 * and list.size()-1, inclusive. (This method has no effect on667 * the size of the list.)668 *669 *

For example, suppose list comprises [t, a, n, k, s].670 * After invoking Collections.rotate(list, 1) (or671 * Collections.rotate(list, -4)), list will comprise672 * [s, t, a, n, k].673 *674 *

Note that this method can usefully be applied to sublists to675 * move one or more elements within a list while preserving the676 * order of the remaining elements. For example, the following idiom677 * moves the element at index j forward to position678 * k (which must be greater than or equal to j):679 *

680 *     Collections.rotate(list.subList(j, k+1), -1);681 * 
682 * To make this concrete, suppose list comprises683 * [a, b, c, d, e]. To move the element at index 1684 * ( b) forward two positions, perform the following invocation:685 *
686 *     Collections.rotate(l.subList(1, 4), -1);687 * 
688 * The resulting list is [a, c, d, b, e].689 *690 *

To move more than one element forward, increase the absolute value691 * of the rotation distance. To move elements backward, use a positive692 * shift distance.693 *694 *

If the specified list is small or implements the {@link

695 * RandomAccess} interface, this implementation exchanges the first696 * element into the location it should go, and then repeatedly exchanges697 * the displaced element into the location it should go until a displaced698 * element is swapped into the first element. If necessary, the process699 * is repeated on the second and successive elements, until the rotation700 * is complete. If the specified list is large and doesn't implement the701 * RandomAccess interface, this implementation breaks the702 * list into two sublist views around index -distance mod size.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 complete705 * description of both algorithms, see Section 2.3 of Jon Bentley's706 * Programming Pearls (Addison-Wesley, 1986).707 *708 *@paramlist the list to be rotated.709 *@paramdistance the distance to rotate the list. There are no710 * constraints on this value; it may be zero, negative, or711 * greater than list.size().712 *@throwsUnsupportedOperationException if the specified list or713 * its list-iterator does not support the set operation.714 *@since1.4715 */

716 //根据指定的距离轮换指定列表中的元素。

717 public static void rotate(List> list, intdistance) {718 if (list instanceof RandomAccess || list.size()

721 rotate2(list, distance);722 }723

724 示例:会改变list的数据结构725 public static voidmain(String[] args) {726 List list = new ArrayList();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 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 void rotate1(List list, intdistance) {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, intdistance) {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 newVal each element e786 * in list such that787 * (oldVal==null ? e==null : oldVal.equals(e)).788 * (This method has no effect on the size of the list.)789 *790 *@param the class of the objects in the list791 *@paramlist the list in which replacement is to occur.792 *@paramoldVal the old value to be replaced.793 *@paramnewVal the new value with which oldVal is to be794 * replaced.795 *@returntrue if list contained one or more elements796 * e such that797 * (oldVal==null ? e==null : oldVal.equals(e)).798 *@throwsUnsupportedOperationException if the specified list or799 * its list-iterator does not support the set operation.800 *@since1.4801 */

802 //使用另一个值替换列表中出现的所有某一指定值。803 //更确切地讲,使用 newVal 替换 list 中满足 (oldVal==null ? e==null : oldVal.equals(e)) 的每个 e 元素。

804 public static boolean replaceAll(Listlist, T oldVal, T newVal) {805 boolean result = false;806 int size =list.size();807 if (size < REPLACEALL_THRESHOLD || list instanceofRandomAccess) {808 if (oldVal==null) {809 for (int i=0; i itr=list.listIterator();825 if (oldVal==null) {826 for (int i=0; i

844 /**

845 * Returns the starting position of the first occurrence of the specified846 * target list within the specified source list, or -1 if there is no847 * such occurrence. More formally, returns the lowest index i848 * such that {@codesource.subList(i, i+target.size()).equals(target)},849 * or -1 if there is no such index. (Returns -1 if850 * {@codetarget.size() > source.size()})851 *852 *

This implementation uses the "brute force" technique of scanning853 * over the source list, looking for a match with the target at each854 * location in turn.855 *856 *@paramsource the list in which to search for the first occurrence857 * of target.858 *@paramtarget the list to search for as a subList of source.859 *@returnthe starting position of the first occurrence of the specified860 * target list within the specified source list, or -1 if there861 * is no such occurrence.862 *@since1.4863 */

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 instanceofRandomAccess)) {872 nextCand:873 for (int candidate = 0; candidate <= maxCandidate; candidate++) {874 for (int i=0, j=candidate; i

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

887 for (int j=0; j

896 }897

898 /**

899 * Returns the starting position of the last occurrence of the specified900 * target list within the specified source list, or -1 if there is no such901 * occurrence. More formally, returns the highest index i902 * such that {@codesource.subList(i, i+target.size()).equals(target)},903 * or -1 if there is no such index. (Returns -1 if904 * {@codetarget.size() > source.size()})905 *906 *

This implementation uses the "brute force" technique of iterating907 * over the source list, looking for a match with the target at each908 * location in turn.909 *910 *@paramsource the list in which to search for the last occurrence911 * of target.912 *@paramtarget the list to search for as a subList of source.913 *@returnthe starting position of the last occurrence of the specified914 * target list within the specified source list, or -1 if there915 * is no such occurrence.916 *@since1.4917 */

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

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

944 for (int j=0; j<=i+1; j++)945 si.previous();946 }947 continuenextCand;948 }949 }950 returncandidate;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 method961 * allows modules to provide users with "read-only" access to internal962 * collections. Query operations on the returned collection "read through"963 * to the specified collection, and attempts to modify the returned964 * collection, whether direct or via its iterator, result in an965 * UnsupportedOperationException.

966 *967 * The returned collection does not pass the hashCode and equals968 * operations through to the backing collection, but relies on969 * Object's equals and hashCode methods. This970 * is necessary to preserve the contracts of these operations in the case971 * that the backing collection is a set or a list.

972 *973 * The returned collection will be serializable if the specified collection974 * is serializable.975 *976 *@param the class of the objects in the collection977 *@paramc the collection for which an unmodifiable view is to be978 * returned.979 *@returnan unmodifiable view of the specified collection.980 */

981 //返回指定 collection 的不可修改视图。此方法允许模块为用户提供对内部 collection 的“只读”访问。982 //在返回的 collection 上执行的查询操作将“读完”指定的 collection。983 //人为的给普通容器加上不可修改的特性

984 public static Collection unmodifiableCollection(Collection extends T>c) {985 return new UnmodifiableCollection<>(c);986 }987

988 /**

989 *@serialinclude990 */

991 static class UnmodifiableCollection implements Collection, 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 newNullPointerException();999 this.c =c;1000 }1001

1002 public int size() {returnc.size();}1003 public boolean isEmpty() {returnc.isEmpty();}1004 public boolean contains(Object o) {returnc.contains(o);}1005 public Object[] toArray() {returnc.toArray();}1006 public T[] toArray(T[] a) {returnc.toArray(a);}1007 public String toString() {returnc.toString();}1008

1009 public Iteratoriterator() {1010 return new Iterator() {1011 private final Iterator extends E> i =c.iterator();1012

1013 public boolean hasNext() {returni.hasNext();}1014 public E next() {returni.next();}1015 public voidremove() {1016 throw newUnsupportedOperationException();1017 }1018 @Override1019 public void forEachRemaining(Consumer super E>action) {1020 //Use backing collection version

1021 i.forEachRemaining(action);1022 }1023 };1024 }1025

1026 public booleanadd(E e) {1027 throw newUnsupportedOperationException();1028 }1029 public booleanremove(Object o) {1030 throw newUnsupportedOperationException();1031 }1032

1033 public boolean containsAll(Collection>coll) {1034 returnc.containsAll(coll);1035 }1036 public boolean addAll(Collection extends E>coll) {1037 throw newUnsupportedOperationException();1038 }1039 public boolean removeAll(Collection>coll) {1040 throw newUnsupportedOperationException();1041 }1042 public boolean retainAll(Collection>coll) {1043 throw newUnsupportedOperationException();1044 }1045 public voidclear() {1046 throw newUnsupportedOperationException();1047 }1048

1049 //Override default methods in Collection

1050 @Override1051 public void forEach(Consumer super E>action) {1052 c.forEach(action);1053 }1054 @Override1055 public boolean removeIf(Predicate super E>filter) {1056 throw newUnsupportedOperationException();1057 }1058 @SuppressWarnings("unchecked")1059 @Override1060 public Spliteratorspliterator() {1061 return (Spliterator)c.spliterator();1062 }1063 @SuppressWarnings("unchecked")1064 @Override1065 public Streamstream() {1066 return (Stream)c.stream();1067 }1068 @SuppressWarnings("unchecked")1069 @Override1070 public StreamparallelStream() {1071 return (Stream)c.parallelStream();1072 }1073 }1074

1075 /**

1076 * Returns an unmodifiable view of the specified set. This method allows1077 * modules to provide users with "read-only" access to internal sets.1078 * Query operations on the returned set "read through" to the specified1079 * set, and attempts to modify the returned set, whether direct or via its1080 * iterator, result in an UnsupportedOperationException.

1081 *1082 * The returned set will be serializable if the specified set1083 * is serializable.1084 *1085 *@param the class of the objects in the set1086 *@params the set for which an unmodifiable view is to be returned.1087 *@returnan unmodifiable view of the specified set.1088 */

1089 //返回指定 set 的不可修改视图。此方法允许模块为用户提供对内部 set 的“只读”访问。1090 //在返回的 set 上执行的查询操作将“读完”指定的 set。

1091 public static Set unmodifiableSet(Set extends T>s) {1092 return new UnmodifiableSet<>(s);1093 }1094

1095 /**

1096 *@serialinclude1097 */

1098 static class UnmodifiableSet extends UnmodifiableCollection

1099 implements Set, 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() {returnc.hashCode();}1105 }1106

1107 /**

1108 * Returns an unmodifiable view of the specified sorted set. This method1109 * allows modules to provide users with "read-only" access to internal1110 * sorted sets. Query operations on the returned sorted set "read1111 * through" to the specified sorted set. Attempts to modify the returned1112 * sorted set, whether direct, via its iterator, or via its1113 * subSet, headSet, or tailSet views, result in1114 * an UnsupportedOperationException.

1115 *1116 * The returned sorted set will be serializable if the specified sorted set1117 * is serializable.1118 *1119 *@param the class of the objects in the set1120 *@params the sorted set for which an unmodifiable view is to be1121 * returned.1122 *@returnan unmodifiable view of the specified sorted set.1123 */

1124 //返回指定有序 set 的不可修改视图。此方法允许模块为用户提供对内部有序 set 的“只读”访问。1125 //在返回的有序 set 上执行的查询操作将“读完”指定的有序 set。

1126 public static SortedSet unmodifiableSortedSet(SortedSets) {1127 return new UnmodifiableSortedSet<>(s);1128 }1129

1130 /**

1131 *@serialinclude1132 */

1133 static class UnmodifiableSortedSet

1134 extends UnmodifiableSet

1135 implements SortedSet, Serializable {1136 private static final long serialVersionUID = -4929149591599911165L;1137 private final SortedSetss;1138

1139 UnmodifiableSortedSet(SortedSet s) {super(s); ss =s;}1140

1141 public Comparator super E> comparator() {returnss.comparator();}1142

1143 public SortedSetsubSet(E fromElement, E toElement) {1144 return new UnmodifiableSortedSet<>(ss.subSet(fromElement,toElement));1145 }1146 public SortedSetheadSet(E toElement) {1147 return new UnmodifiableSortedSet<>(ss.headSet(toElement));1148 }1149 public SortedSettailSet(E fromElement) {1150 return new UnmodifiableSortedSet<>(ss.tailSet(fromElement));1151 }1152

1153 public E first() {returnss.first();}1154 public E last() {returnss.last();}1155 }1156

1157

1158

1159

1160

1161

1162 //Synch Wrappers

1163

1164 /**

1165 * Returns a synchronized (thread-safe) collection backed by the specified1166 * collection. In order to guarantee serial access, it is critical that1167 * all access to the backing collection is accomplished1168 * through the returned collection.

1169 *1170 * It is imperative that the user manually synchronize on the returned1171 * collection when traversing it via {@linkIterator}, {@linkSpliterator}1172 * or {@linkStream}:1173 *

1174 *  Collection c = Collections.synchronizedCollection(myCollection);1175 *     ...1176 *  synchronized (c) {1177 *      Iterator i = c.iterator(); // Must be in the synchronized block1178 *      while (i.hasNext())1179 *         foo(i.next());1180 *  }1181 * 
1182 * Failure to follow this advice may result in non-deterministic behavior.1183 *1184 *

The returned collection does not pass the {@codehashCode}1185 * and {@codeequals} operations through to the backing collection, but1186 * relies on {@codeObject}'s equals and hashCode methods. This is1187 * necessary to preserve the contracts of these operations in the case1188 * that the backing collection is a set or a list.

1189 *1190 * The returned collection will be serializable if the specified collection1191 * is serializable.1192 *1193 *@param the class of the objects in the collection1194 *@paramc the collection to be "wrapped" in a synchronized collection.1195 *@returna synchronized view of the specified collection.1196 */

1197 //返回指定 collection 支持的同步(线程安全的)collection。1198 //为了保证按顺序访问,必须通过返回的 collection 完成所有对底层实现 collection 的访问。

1199 public static Collection synchronizedCollection(Collectionc) {1200 return new SynchronizedCollection<>(c);1201 }1202

1203 static Collection synchronizedCollection(Collectionc, Object mutex) {1204 return new SynchronizedCollection<>(c, mutex);1205 }1206

1207 /**

1208 *@serialinclude1209 */

1210 static class SynchronizedCollection implements Collection, Serializable {1211 private static final long serialVersionUID = 3053995032091335093L;1212

1213 final Collection c; //Backing Collection

1214 final Object mutex; //Object on which to synchronize

1215

1216 SynchronizedCollection(Collectionc) {1217 this.c =Objects.requireNonNull(c);1218 mutex = this;1219 }1220

1221 SynchronizedCollection(Collectionc, Object mutex) {1222 this.c =Objects.requireNonNull(c);1223 this.mutex =Objects.requireNonNull(mutex);1224 }1225

1226 public intsize() {1227 synchronized (mutex) {returnc.size();}1228 }1229 public booleanisEmpty() {1230 synchronized (mutex) {returnc.isEmpty();}1231 }1232 public booleancontains(Object o) {1233 synchronized (mutex) {returnc.contains(o);}1234 }1235 publicObject[] toArray() {1236 synchronized (mutex) {returnc.toArray();}1237 }1238 public T[] toArray(T[] a) {1239 synchronized (mutex) {returnc.toArray(a);}1240 }1241

1242 public Iteratoriterator() {1243 return c.iterator(); //Must be manually synched by user!

1244 }1245

1246 public booleanadd(E e) {1247 synchronized (mutex) {returnc.add(e);}1248 }1249 public booleanremove(Object o) {1250 synchronized (mutex) {returnc.remove(o);}1251 }1252

1253 public boolean containsAll(Collection>coll) {1254 synchronized (mutex) {returnc.containsAll(coll);}1255 }1256 public boolean addAll(Collection extends E>coll) {1257 synchronized (mutex) {returnc.addAll(coll);}1258 }1259 public boolean removeAll(Collection>coll) {1260 synchronized (mutex) {returnc.removeAll(coll);}1261 }1262 public boolean retainAll(Collection>coll) {1263 synchronized (mutex) {returnc.retainAll(coll);}1264 }1265 public voidclear() {1266 synchronized(mutex) {c.clear();}1267 }1268 publicString toString() {1269 synchronized (mutex) {returnc.toString();}1270 }1271 //Override default methods in Collection

1272 @Override1273 public void forEach(Consumer super E>consumer) {1274 synchronized(mutex) {c.forEach(consumer);}1275 }1276 @Override1277 public boolean removeIf(Predicate super E>filter) {1278 synchronized (mutex) {returnc.removeIf(filter);}1279 }1280 @Override1281 public Spliteratorspliterator() {1282 return c.spliterator(); //Must be manually synched by user!

1283 }1284 @Override1285 public Streamstream() {1286 return c.stream(); //Must be manually synched by user!

1287 }1288 @Override1289 public StreamparallelStream() {1290 return c.parallelStream(); //Must be manually synched by user!

1291 }1292 private void writeObject(ObjectOutputStream s) throwsIOException {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 an1303 * immediate {@linkClassCastException}. Assuming a collection1304 * contains no incorrectly typed elements prior to the time a1305 * dynamically typesafe view is generated, and that all subsequent1306 * access to the collection takes place through the view, it is1307 * guaranteed that the collection cannot contain an incorrectly1308 * typed element.1309 *1310 *

The generics mechanism in the language provides compile-time1311 * (static) type checking, but it is possible to defeat this mechanism1312 * with unchecked casts. Usually this is not a problem, as the compiler1313 * 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 is1316 * imperative that the library code not corrupt the collection by1317 * inserting an element of the wrong type.1318 *1319 *

Another use of dynamically typesafe views is debugging. Suppose a1320 * program fails with a {@codeClassCastException}, indicating that an1321 * incorrectly typed element was put into a parameterized collection.1322 * Unfortunately, the exception can occur at any time after the erroneous1323 * element is inserted, so it typically provides little or no information1324 * as to the real source of the problem. If the problem is reproducible,1325 * one can quickly determine its source by temporarily modifying the1326 * program to wrap the collection with a dynamically typesafe view.1327 * For example, this declaration:1328 *

 {@code

1329 * Collection c = new HashSet<>();1330 * }1331 * may be replaced temporarily by this one:1332 *

 {@code

1333 * Collection c = Collections.checkedCollection(1334 * new HashSet<>(), String.class);1335 * }1336 * Running the program again will cause it to fail at the point where1337 * an incorrectly typed element is inserted into the collection, clearly1338 * identifying the source of the problem. Once the problem is fixed, the1339 * modified declaration may be reverted back to the original.1340 *1341 *

The returned collection does not pass the hashCode and equals1342 * operations through to the backing collection, but relies on1343 * {@codeObject}'s {@codeequals} and {@codehashCode} methods. This1344 * is necessary to preserve the contracts of these operations in the case1345 * that the backing collection is a set or a list.1346 *1347 *

The returned collection will be serializable if the specified1348 * collection is serializable.1349 *1350 *

Since {@codenull} is considered to be a value of any reference1351 * type, the returned collection permits insertion of null elements1352 * whenever the backing collection does.1353 *1354 *@param the class of the objects in the collection1355 *@paramc the collection for which a dynamically typesafe view is to be1356 * returned1357 *@paramtype the type of element that {@codec} is permitted to hold1358 *@returna dynamically typesafe view of the specified collection1359 *@since1.51360 */

1361 //返回指定 collection 的一个动态类型安全视图。用以检测元素类型是否正确。

1362 public static Collection checkedCollection(Collectionc,1363 Classtype) {1364 return new CheckedCollection<>(c, type);1365 }1366

1367 @SuppressWarnings("unchecked")1368 static T[] zeroLengthArray(Classtype) {1369 return (T[]) Array.newInstance(type, 0);1370 }1371

1372 /**

1373 *@serialinclude1374 */

1375 static class CheckedCollection implements Collection, Serializable {1376 private static final long serialVersionUID = 1578914078182001775L;1377

1378 final Collectionc;1379 final Classtype;1380

1381 @SuppressWarnings("unchecked")1382 E typeCheck(Object o) {1383 if (o != null && !type.isInstance(o))1384 throw newClassCastException(badElementMsg(o));1385 return(E) o;1386 }1387

1388 privateString badElementMsg(Object o) {1389 return "Attempt to insert " + o.getClass() +

1390 " element into collection with element type " +type;1391 }1392

1393 CheckedCollection(Collection c, Classtype) {1394 this.c = Objects.requireNonNull(c, "c");1395 this.type = Objects.requireNonNull(type, "type");1396 }1397

1398 public int size() { returnc.size(); }1399 public boolean isEmpty() { returnc.isEmpty(); }1400 public boolean contains(Object o) { returnc.contains(o); }1401 public Object[] toArray() { returnc.toArray(); }1402 public T[] toArray(T[] a) { returnc.toArray(a); }1403 public String toString() { returnc.toString(); }1404 public boolean remove(Object o) { returnc.remove(o); }1405 public voidclear() { c.clear(); }1406

1407 public boolean containsAll(Collection>coll) {1408 returnc.containsAll(coll);1409 }1410 public boolean removeAll(Collection>coll) {1411 returnc.removeAll(coll);1412 }1413 public boolean retainAll(Collection>coll) {1414 returnc.retainAll(coll);1415 }1416

1417 public Iteratoriterator() {1418 //JDK-6363904 - unwrapped iterator could be typecast to1419 //ListIterator with unsafe set()

1420 final Iterator it =c.iterator();1421 return new Iterator() {1422 public boolean hasNext() { returnit.hasNext(); }1423 public E next() { returnit.next(); }1424 public voidremove() { it.remove(); }};1425 }1426

1427 public boolean add(E e) { returnc.add(typeCheck(e)); }1428

1429 private E[] zeroLengthElementArray; //Lazily initialized

1430

1431 privateE[] zeroLengthElementArray() {1432 return zeroLengthElementArray != null ?zeroLengthElementArray :1433 (zeroLengthElementArray =zeroLengthArray(type));1434 }1435

1436 @SuppressWarnings("unchecked")1437 Collection 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 a1449 //reference to the returned array and storing a bad1450 //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) Arrays.asList(a);1457 }1458

1459 public boolean addAll(Collection extends E>coll) {1460 //Doing things this way insulates us from concurrent changes1461 //in the contents of coll and provides all-or-nothing1462 //semantics (which we wouldn't get if we type-checked each1463 //element as we added it)

1464 returnc.addAll(checkedCopyOf(coll));1465 }1466

1467 //Override default methods in Collection

1468 @Override1469 public void forEach(Consumer super E>action) {c.forEach(action);}1470 @Override1471 public boolean removeIf(Predicate super E>filter) {1472 returnc.removeIf(filter);1473 }1474 @Override1475 public Spliterator spliterator() {returnc.spliterator();}1476 @Override1477 public Stream stream() {returnc.stream();}1478 @Override1479 public Stream parallelStream() {returnc.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 the class of the objects in the list1493 *@paramo the sole object to be stored in the returned list.1494 *@returnan immutable list containing only the specified object.1495 *@since1.31496 */

1497 //返回一个只包含指定对象的不可变列表。返回的列表是可序列化的。

1498 public static ListsingletonList(T o) {1499 return new SingletonList<>(o);1500 }1501

1502 /**

1503 *@serialinclude1504 */

1505 private static class SingletonList

1506 extends AbstractList

1507 implementsRandomAccess, Serializable {1508

1509 private static final long serialVersionUID = 3093736618740652951L;1510

1511 private finalE element;1512

1513 SingletonList(E obj) {element =obj;}1514

1515 public Iteratoriterator() {1516 returnsingletonIterator(element);1517 }1518

1519 public int size() {return 1;}1520

1521 public boolean contains(Object obj) {returneq(obj, element);}1522

1523 public E get(intindex) {1524 if (index != 0)1525 throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");1526 returnelement;1527 }1528

1529 //Override default methods for Collection

1530 @Override1531 public void forEach(Consumer super E>action) {1532 action.accept(element);1533 }1534 @Override1535 public boolean removeIf(Predicate super E>filter) {1536 throw newUnsupportedOperationException();1537 }1538 @Override1539 public void replaceAll(UnaryOperatoroperator) {1540 throw newUnsupportedOperationException();1541 }1542 @Override1543 public void sort(Comparator super E>c) {1544 }1545 @Override1546 public Spliteratorspliterator() {1547 returnsingletonSpliterator(element);1548 }1549 }1550

1551

1552 //Miscellaneous

1553

1554 /**

1555 * Returns an immutable list consisting of n copies of the1556 * specified object. The newly allocated data object is tiny (it contains1557 * a single reference to the data object). This method is useful in1558 * combination with the List.addAll method to grow lists.1559 * The returned list is serializable.1560 *1561 *@param the class of the object to copy and of the objects1562 * in the returned list.1563 *@paramn the number of elements in the returned list.1564 *@paramo the element to appear repeatedly in the returned list.1565 *@returnan immutable list consisting of n copies of the1566 * specified object.1567 *@throwsIllegalArgumentException if {@coden < 0}1568 *@seeList#addAll(Collection)1569 *@seeList#addAll(int, Collection)1570 */

1571 //返回由指定对象的 n 个副本组成的不可变列表。1572 //新分配的数据对象非常小(它只包含一个对该数据对象的引用)。在通过与 List.addAll 方法组合来增大列表时,此方法很有用

1573 public static List nCopies(intn, T o) {1574 if (n < 0)1575 throw new IllegalArgumentException("List length = " +n);1576 return new CopiesList<>(n, o);1577 }1578

1579 /**

1580 *@serialinclude1581 */

1582 private static class CopiesList

1583 extends AbstractList

1584 implementsRandomAccess, Serializable1585 {1586 private static final long serialVersionUID = 2739099268398711800L;1587

1588 final intn;1589 finalE element;1590

1591 CopiesList(intn, E e) {1592 assert n >= 0;1593 this.n =n;1594 element =e;1595 }1596

1597 public intsize() {1598 returnn;1599 }1600

1601 public booleancontains(Object obj) {1602 return n != 0 &&eq(obj, element);1603 }1604

1605 public intindexOf(Object o) {1606 return contains(o) ? 0 : -1;1607 }1608

1609 public intlastIndexOf(Object o) {1610 return contains(o) ? n - 1 : -1;1611 }1612

1613 public E get(intindex) {1614 if (index < 0 || index >=n)1615 throw new IndexOutOfBoundsException("Index: "+index+

1616 ", Size: "+n);1617 returnelement;1618 }1619

1620 publicObject[] toArray() {1621 final Object[] a = newObject[n];1622 if (element != null)1623 Arrays.fill(a, 0, n, element);1624 returna;1625 }1626

1627 @SuppressWarnings("unchecked")1628 public T[] toArray(T[] a) {1629 final int n = this.n;1630 if (a.length n)1638 a[n] = null;1639 }1640 returna;1641 }1642

1643 public List subList(int fromIndex, inttoIndex) {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 @Override1656 public Streamstream() {1657 return IntStream.range(0, n).mapToObj(i ->element);1658 }1659

1660 @Override1661 public StreamparallelStream() {1662 return IntStream.range(0, n).parallel().mapToObj(i ->element);1663 }1664

1665 @Override1666 public Spliteratorspliterator() {1667 returnstream().spliterator();1668 }1669 }1670

1671 /**

1672 * Returns a comparator that imposes the reverse of the natural1673 * ordering on a collection of objects that implement the1674 * {@codeComparable} interface. (The natural ordering is the ordering1675 * imposed by the objects' own {@codecompareTo} method.) This enables a1676 * simple idiom for sorting (or maintaining) collections (or arrays) of1677 * objects that implement the {@codeComparable} interface in1678 * reverse-natural-order. For example, suppose {@codea} is an array of1679 * strings. Then:

1680 *          Arrays.sort(a, Collections.reverseOrder());1681 * 
sorts the array in reverse-lexicographic (alphabetical) order.

1682 *1683 * The returned comparator is serializable.1684 *1685 *@param the class of the objects compared by the comparator1686 *@returnA comparator that imposes the reverse of the natural1687 * ordering on a collection of objects that implement1688 * the Comparable interface.1689 *@seeComparable1690 */

1691 //返回一个比较器,它强行逆转实现了 Comparable 接口的对象 collection 的自然顺序。

1692 @SuppressWarnings("unchecked")1693 public static ComparatorreverseOrder() {1694 return (Comparator) ReverseComparator.REVERSE_ORDER;1695 }1696

1697 /**

1698 *@serialinclude1699 */

1700 private static classReverseComparator1701 implements Comparator>, Serializable {1702

1703 private static final long serialVersionUID = 7207038068494060240L;1704

1705 static finalReverseComparator REVERSE_ORDER1706 = newReverseComparator();1707

1708 public int compare(Comparable c1, Comparablec2) {1709 returnc2.compareTo(c1);1710 }1711

1712 private Object readResolve() { returnCollections.reverseOrder(); }1713

1714 @Override1715 public Comparator>reversed() {1716 returnComparator.naturalOrder();1717 }1718 }1719

1720 /**

1721 * Returns a comparator that imposes the reverse ordering of the specified1722 * comparator. If the specified comparator is {@codenull}, this method is1723 * equivalent to {@link#reverseOrder()} (in other words, it returns a1724 * comparator that imposes the reverse of the natural ordering on1725 * a collection of objects that implement the Comparable interface).1726 *1727 *

The returned comparator is serializable (assuming the specified1728 * comparator is also serializable or {@codenull}).1729 *1730 *@param the class of the objects compared by the comparator1731 *@paramcmp a comparator who's ordering is to be reversed by the returned1732 * comparator or {@codenull}1733 *@returnA comparator that imposes the reverse ordering of the1734 * specified comparator.1735 *@since1.51736 */

1737 //返回一个比较器,它强行逆转指定比较器的顺序。

1738 public static Comparator reverseOrder(Comparatorcmp) {1739 if (cmp == null)1740 returnreverseOrder();1741

1742 if (cmp instanceofReverseComparator2)1743 return ((ReverseComparator2)cmp).cmp;1744

1745 return new ReverseComparator2<>(cmp);1746 }1747

1748 /**

1749 *@serialinclude1750 */

1751 private static class ReverseComparator2 implements Comparator,1752 Serializable1753 {1754 private static final long serialVersionUID = 4374092139857L;1755

1756 /**

1757 * The comparator specified in the static factory. This will never1758 * be null, as the static factory returns a ReverseComparator1759 * instance if its argument is null.1760 *1761 *@serial

1762 */

1763 final Comparatorcmp;1764

1765 ReverseComparator2(Comparatorcmp) {1766 assert cmp != null;1767 this.cmp =cmp;1768 }1769

1770 public intcompare(T t1, T t2) {1771 returncmp.compare(t2, t1);1772 }1773

1774 public booleanequals(Object o) {1775 return (o == this) ||

1776 (o instanceof ReverseComparator2 &&

1777 cmp.equals(((ReverseComparator2)o).cmp));1778 }1779

1780 public inthashCode() {1781 return cmp.hashCode() ^Integer.MIN_VALUE;1782 }1783

1784 @Override1785 public Comparatorreversed() {1786 returncmp;1787 }1788 }1789

1790

1791

1792 /**

1793 * Returns an array list containing the elements returned by the1794 * specified enumeration in the order they are returned by the1795 * enumeration. This method provides interoperability between1796 * legacy APIs that return enumerations and new APIs that require1797 * collections.1798 *1799 *@param the class of the objects returned by the enumeration1800 *@parame enumeration providing elements for the returned1801 * array list1802 *@returnan array list containing the elements returned1803 * by the specified enumeration.1804 *@since1.41805 *@seeEnumeration1806 *@seeArrayList1807 */

1808 public static ArrayList list(Enumeratione) {1809 ArrayList l = new ArrayList<>();1810 while(e.hasMoreElements())1811 l.add(e.nextElement());1812 returnl;1813 }1814

1815 /**

1816 * Returns the number of elements in the specified collection equal to the1817 * specified object. More formally, returns the number of elements1818 * e in the collection such that1819 * (o == null ? e == null : o.equals(e)).1820 *1821 *@paramc the collection in which to determine the frequency1822 * of o1823 *@paramo the object whose frequency is to be determined1824 *@returnthe number of elements in {@codec} equal to {@codeo}1825 *@throwsNullPointerException if c is null1826 *@since1.51827 */

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 returnresult;1842 }1843

1844 /**

1845 * Returns {@codetrue} if the two specified collections have no1846 * elements in common.1847 *1848 *

Care must be exercised if this method is used on collections that1849 * do not comply with the general contract for {@codeCollection}.1850 * Implementations may elect to iterate over either collection and test1851 * for containment in the other collection (or to perform any equivalent1852 * computation). If either collection uses a nonstandard equality test1853 * (as does a {@linkSortedSet} whose ordering is not compatible with1854 * equals, or the key set of an {@linkIdentityHashMap}), both1855 * collections must use the same nonstandard equality test, or the1856 * result of this method is undefined.1857 *1858 *

Care must also be exercised when using collections that have1859 * restrictions on the elements that they may contain. Collection1860 * implementations are allowed to throw exceptions for any operation1861 * involving elements they deem ineligible. For absolute safety the1862 * specified collections should contain only elements which are1863 * eligible elements for both collections.1864 *1865 *

Note that it is permissible to pass the same collection in both1866 * parameters, in which case the method will return {@codetrue} if and1867 * only if the collection is empty.1868 *1869 *@paramc1 a collection1870 *@paramc2 a collection1871 *@return{@codetrue} if the two specified collections have no1872 * elements in common.1873 *@throwsNullPointerException if either collection is {@codenull}.1874 *@throwsNullPointerException if one collection contains a {@codenull}1875 * element and {@codenull} is not an eligible element for the other collection.1876 * (optional)1877 *@throwsClassCastException if one collection contains an element that is1878 * of a type which is ineligible for the other collection.1879 * (optional)1880 *@since1.51881 */

1882

1883 //如果两个指定 collection 中没有相同的元素,则返回 true。1884 //如果将此方法用在不符合 Collection 常规协定的 collection 上,则必须小心。1885 //实现可以在任一 collection 上进行迭代,测试元素是否包含在另一个 collection 中(或执行任何等效的计算)。1886 //如果任一 collection 使用了一个非标准的相等性测试(比如顺序不是与 equals 一致的 SortedSet,1887 //或者 IdentityHashMap 的键集),则两个 collection1888 //都必须使用相同的非标准相等性测试,否则此方法的结果是不确定的。1889 //注意,允许在两个参数中传递相同的 collection,在这种情况下,当且仅当 collection 为空时此方法返回 true。

1890 public static boolean disjoint(Collection> c1, Collection>c2) {1891 //The collection to be used for contains(). Preference is given to1892 //the collection who's contains() has lower O() complexity.

1893 Collection> contains =c2;1894 //The collection to be iterated. If the collections' contains() impl1895 //are of different O() complexity, the collection with slower1896 //contains() will be used for iteration. For collections who's1897 //contains() are of the same complexity then best performance is1898 //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 instanceofSet) {1907 //Use c1 for contains as a Set's contains() is expected to perform1908 //better than O(N/2)

1909 iterate =c2;1910 contains =c1;1911 } else if (!(c2 instanceofSet)) {1912 //Both are mere Collections. Iterate over smaller collection.1913 //Example: If c1 contains 3 elements and c2 contains 50 elements and1914 //assuming contains() requires ceiling(N/2) comparisons then1915 //checking for all c1 elements in c2 would require 75 comparisons1916 //(3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring1917 //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 {@linkDeque} as a Last-in-first-out (Lifo)1946 * {@linkQueue}. Method add is mapped to push,1947 * remove is mapped to pop and so on. This1948 * view can be useful when you would like to use a method1949 * requiring a Queue but you need Lifo ordering.1950 *1951 *

Each method invocation on the queue returned by this method1952 * results in exactly one method invocation on the backing deque, with1953 * one exception. The {@linkQueue#addAll addAll} method is1954 * implemented as a sequence of {@linkDeque#addFirst addFirst}1955 * invocations on the backing deque.1956 *1957 *@param the class of the objects in the deque1958 *@paramdeque the deque1959 *@returnthe queue1960 *@since1.61961 */

1962 //以后进先出 (Lifo) Queue 的形式返回某个 Deque 的视图。1963 //方法 add 被映射到 push,remove 被映射到 pop 等等。1964 //在希望使用某一方法获取一个 Queue 并且需要它具有 Lifo 顺序时,此方法很有用。1965 //每次在此方法返回的队列上调用方法都将导致在底层实现队列上调用该方法一次,

1966 并伴随一个异常。addAll 方法是作为底层实现队列上的 addFirst 调用序列实现的。1967 public static Queue asLifoQueue(Dequedeque) {1968 return new AsLIFOQueue<>(deque);1969 }1970

1971 /**

1972 *@serialinclude1973 */

1974 static class AsLIFOQueue extends AbstractQueue

1975 implements Queue, Serializable {1976 private static final long serialVersionUID = 1802017725587941708L;1977 private final Dequeq;1978 AsLIFOQueue(Deque q) { this.q =q; }1979 public boolean add(E e) { q.addFirst(e); return true; }1980 public boolean offer(E e) { returnq.offerFirst(e); }1981 public E poll() { returnq.pollFirst(); }1982 public E remove() { returnq.removeFirst(); }1983 public E peek() { returnq.peekFirst(); }1984 public E element() { returnq.getFirst(); }1985 public voidclear() { q.clear(); }1986 public int size() { returnq.size(); }1987 public boolean isEmpty() { returnq.isEmpty(); }1988 public boolean contains(Object o) { returnq.contains(o); }1989 public boolean remove(Object o) { returnq.remove(o); }1990 public Iterator iterator() { returnq.iterator(); }1991 public Object[] toArray() { returnq.toArray(); }1992 public T[] toArray(T[] a) { returnq.toArray(a); }1993 public String toString() { returnq.toString(); }1994 public boolean containsAll(Collection> c) {returnq.containsAll(c);}1995 public boolean removeAll(Collection> c) {returnq.removeAll(c);}1996 public boolean retainAll(Collection> c) {returnq.retainAll(c);}1997 //We use inherited addAll; forwarding addAll would be wrong1998

1999 //Override default methods in Collection

2000 @Override2001 public void forEach(Consumer super E>action) {q.forEach(action);}2002 @Override2003 public boolean removeIf(Predicate super E>filter) {2004 returnq.removeIf(filter);2005 }2006 @Override2007 public Spliterator spliterator() {returnq.spliterator();}2008 @Override2009 public Stream stream() {returnq.stream();}2010 @Override2011 public Stream parallelStream() {returnq.parallelStream();}2012 }2013 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值