正文:

一、概述:

此类完全由在 collection 上进行操作或返回 collection 的静态方法组成。它包含在 collection 上操作的多态算法,即“包装器”,包装器返回由指定 collection 支持的新 collection,以及少数其他内容。

如果为此类的方法所提供的 collection 或类对象为 null,则这些方法都将抛出 NullPointerException

此类中所含多态算法的文档通常包括对实现 的简短描述。应该将这类描述视为实现注意事项,而不是规范 的一部分。实现者应该可以随意使用其他算法替代,只要遵循规范本身即可。(例如,sort 使用的算法不一定是合并排序算法,但它必须是稳定的。)

此类中包含的“破坏性”算法,即可修改其所操作的 collection 的算法,该算法被指定在 collection 不支持适当的可变基元(比如 set 方法)时抛出 UnsupportedOperationException。如果调用不会对 collection 产生任何影响,那么这些算法可能(但不要求)抛出此异常。例如,在已经排序的、不可修改列表上调用 sort 方法可能会(也可能不会)抛出 UnsupportedOperationException

二、拓展点

1,<T> Comparator<T> reverseOrder()分析

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

JDK1.8源码Collections的更多相关文章

  1. 【JUC】JDK1.8源码分析之ArrayBlockingQueue(三)

    一.前言 在完成Map下的并发集合后,现在来分析ArrayBlockingQueue,ArrayBlockingQueue可以用作一个阻塞型队列,支持多任务并发操作,有了之前看源码的积累,再看Arra ...

  2. JDK1.8源码阅读系列之三:Vector

    本篇随笔主要描述的是我阅读 Vector 源码期间的对于 Vector 的一些实现上的个人理解,用于个人备忘,有不对的地方,请指出- 先来看一下 Vector 的继承图: 可以看出,Vector 的直 ...

  3. 【1】【JUC】JDK1.8源码分析之ArrayBlockingQueue,LinkedBlockingQueue

    概要: ArrayBlockingQueue的内部是通过一个可重入锁ReentrantLock和两个Condition条件对象来实现阻塞 注意这两个Condition即ReentrantLock的Co ...

  4. 【集合框架】JDK1.8源码分析HashSet && LinkedHashSet(八)

    一.前言 分析完了List的两个主要类之后,我们来分析Set接口下的类,HashSet和LinkedHashSet,其实,在分析完HashMap与LinkedHashMap之后,再来分析HashSet ...

  5. 【集合框架】JDK1.8源码分析之HashMap(一) 转载

    [集合框架]JDK1.8源码分析之HashMap(一)   一.前言 在分析jdk1.8后的HashMap源码时,发现网上好多分析都是基于之前的jdk,而Java8的HashMap对之前做了较大的优化 ...

  6. 【集合框架】JDK1.8源码分析之ArrayList详解(一)

    [集合框架]JDK1.8源码分析之ArrayList详解(一) 一. 从ArrayList字表面推测 ArrayList类的命名是由Array和List单词组合而成,Array的中文意思是数组,Lis ...

  7. 集合之TreeSet(含JDK1.8源码分析)

    一.前言 前面分析了Set接口下的hashSet和linkedHashSet,下面接着来看treeSet,treeSet的底层实现是基于treeMap的. 四个关注点在treeSet上的答案 二.tr ...

  8. 集合之LinkedHashSet(含JDK1.8源码分析)

    一.前言 上篇已经分析了Set接口下HashSet,我们发现其操作都是基于hashMap的,接下来看LinkedHashSet,其底层实现都是基于linkedHashMap的. 二.linkedHas ...

  9. 集合之HashSet(含JDK1.8源码分析)

    一.前言 我们已经分析了List接口下的ArrayList和LinkedList,以及Map接口下的HashMap.LinkedHashMap.TreeMap,接下来看的是Set接口下HashSet和 ...

随机推荐

  1. word count程序,以及困扰人的宽字符与字符

    一个Word Count程序,由c++完成,有行数.词数.能完成路径下文件的遍历. 遍历文件部分的代码如下: void FindeFile(wchar_t *pFilePath) { CFileFin ...

  2. [51CTO]区块链在美国:10个案例、10个问题和5个解决方案

    区块链在美国:10个案例.10个问题和5个解决方案 近日,美国国际战略研究中心(CSIS, Center for Strategic and International Studies)发布报告< ...

  3. 一本通1626【例 2】Hankson 的趣味题

    1626:[例 2]Hankson 的趣味题 题目描述 Hanks 博士是BT (Bio-Tech,生物技术) 领域的知名专家,他的儿子名叫Hankson.现在,刚刚放学回家的Hankson 正在思考 ...

  4. anaconda的spyder打不开

    因为最近一段时间没有用Spyder,今天使用时,发现Spyder又又打不开了. 之前遇到Spyder打不开的情况时,是根据这里的教程:删除.matplotlib和.spyder两个文件,但这次删除这两 ...

  5. [代码]--GridControl使用技巧总结,更新中...

    1如何禁用GridControl中单击列弹出右键菜单 设置Run Design->OptionsMenu->EnableColumnMenu 设置为:false 2如何定位到第一条数据/记 ...

  6. BZOJ5462 APIO2018新家(线段树+堆)

    一个显然的做法是二分答案后转化为查询区间颜色数,可持久化线段树记录每个位置上一个同色位置,离线后set+树状数组套线段树维护.这样是三个log的. 注意到我们要知道的其实只是是否所有颜色都在该区间出现 ...

  7. SQL问题(面试题)

    面试完后在本地mysql数据库中重现了该问题 数据表stuscore信息如下: 1.计算每个人的总成绩,并且排名(要求显示字段 学号 姓名 总成绩)SELECT stuid AS 学号,NAME AS ...

  8. 【BZOJ1303】[CQOI2009]中位数图(模拟)

    [BZOJ1303][CQOI2009]中位数图(模拟) 题面 BZOJ 洛谷 题解 把大于\(b\)的数设为\(1\),小于\(b\)的数设为\(-1\).显然询问就是有多少个横跨了\(b\)这个数 ...

  9. 洛谷 P1361 小M的作物 解题报告

    P1361 小M的作物 题目描述 小M在MC里开辟了两块巨大的耕地\(A\)和\(B\)(你可以认为容量是无穷),现在,小\(P\)有\(n\)中作物的种子,每种作物的种子有1个(就是可以种一棵作物) ...

  10. spring data jpa查询部分字段、多余附加字段

    spring data jpa查询部分字段 第一种方法:使用 model 查询时转化 首先建立一个 model ,写上自己想要查询的字段,然后写上构造函数,这步很重要,因为spring jpa 转化时 ...