-
Notifications
You must be signed in to change notification settings - Fork 668
/
Collections.java
6833 lines (5805 loc) · 239 KB
/
Collections.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* This class consists exclusively of static methods that operate on or return
* collections. It contains polymorphic algorithms that operate on
* collections, "wrappers", which return a new collection backed by a
* specified collection, and a few other odds and ends.
*
* <p>The methods of this class all throw a {@code NullPointerException}
* if the collections or class objects provided to them are null.
*
* <p>The documentation for the polymorphic algorithms contained in this class
* generally includes a brief description of the <i>implementation</i>. Such
* descriptions should be regarded as <i>implementation notes</i>, rather than
* parts of the <i>specification</i>. Implementors should feel free to
* substitute other algorithms, so long as the specification itself is adhered
* to. (For example, the algorithm used by {@code sort} does not have to be
* a mergesort, but it does have to be <i>stable</i>.)
*
* <p>The "destructive" algorithms contained in this class, that is, the
* algorithms that modify the collection on which they operate, are specified
* to throw {@code UnsupportedOperationException} if the collection does not
* support the appropriate mutation primitive(s), such as the {@code set}
* method. These algorithms may, but are not required to, throw this
* exception if an invocation would have no effect on the collection. For
* example, invoking the {@code sort} method on an unmodifiable list that is
* already sorted may or may not throw {@code UnsupportedOperationException}.
*
* <p>This class is a member of the
* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
* Java Collections Framework</a>.
*
* @author Josh Bloch
* @author Neal Gafter
* @see Collection
* @see Set
* @see List
* @see Map
* @since 1.2
*/
// 容器工具类
public class Collections {
// Suppresses default constructor, ensuring non-instantiability.
private Collections() {
}
/*
* Tuning parameters for algorithms - Many of the List algorithms have
* two implementations, one of which is appropriate for RandomAccess
* lists, the other for "sequential." Often, the random access variant
* yields better performance on small sequential access lists. The
* tuning parameters below determine the cutoff point for what constitutes
* a "small" sequential access list for each algorithm. The values below
* were empirically determined to work well for LinkedList. Hopefully
* they should be reasonable for other sequential access List
* implementations. Those doing performance work on this code would
* do well to validate the values of these parameters from time to time.
* (The first word of each tuning parameter name is the algorithm to which
* it applies.)
*/
private static final int BINARYSEARCH_THRESHOLD = 5000;
private static final int REVERSE_THRESHOLD = 18;
private static final int SHUFFLE_THRESHOLD = 5;
private static final int FILL_THRESHOLD = 25;
private static final int ROTATE_THRESHOLD = 100;
private static final int COPY_THRESHOLD = 10;
private static final int REPLACEALL_THRESHOLD = 11;
private static final int INDEXOFSUBLIST_THRESHOLD = 35;
private static Random r;
/*▼ List操作 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Sorts the specified list into ascending order, according to the
* {@linkplain Comparable natural ordering} of its elements.
* All elements in the list must implement the {@link Comparable}
* interface. Furthermore, all elements in the list must be
* <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}
* must not throw a {@code ClassCastException} for any elements
* {@code e1} and {@code e2} in the list).
*
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will
* not be reordered as a result of the sort.
*
* <p>The specified list must be modifiable, but need not be resizable.
*
* @param <T> the class of the objects in the list
* @param list the list to be sorted.
*
* @throws ClassCastException if the list contains elements that are not
* <i>mutually comparable</i> (for example, strings and integers).
* @throws UnsupportedOperationException if the specified list's
* list-iterator does not support the {@code set} operation.
* @throws IllegalArgumentException (optional) if the implementation
* detects that the natural ordering of the list elements is
* found to violate the {@link Comparable} contract
* @implNote This implementation defers to the {@link List#sort(Comparator)}
* method using the specified list and a {@code null} comparator.
* @see List#sort(Comparator)
*/
// 对指定的list进行排序(使用内部比较器)
@SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> void sort(List<T> list) {
list.sort(null);
}
/**
* Sorts the specified list according to the order induced by the
* specified comparator. All elements in the list must be <i>mutually
* comparable</i> using the specified comparator (that is,
* {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
* for any elements {@code e1} and {@code e2} in the list).
*
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will
* not be reordered as a result of the sort.
*
* <p>The specified list must be modifiable, but need not be resizable.
*
* @param <T> the class of the objects in the list
* @param list the list to be sorted.
* @param c the comparator to determine the order of the list. A
* {@code null} value indicates that the elements' <i>natural
* ordering</i> should be used.
*
* @throws ClassCastException if the list contains elements that are not
* <i>mutually comparable</i> using the specified comparator.
* @throws UnsupportedOperationException if the specified list's
* list-iterator does not support the {@code set} operation.
* @throws IllegalArgumentException (optional) if the comparator is
* found to violate the {@link Comparator} contract
* @implNote This implementation defers to the {@link List#sort(Comparator)}
* method using the specified list and comparator.
* @see List#sort(Comparator)
*/
// 对指定的list进行排序(使用指定的外部比较器)
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
/**
* Searches the specified list for the specified object using the binary
* search algorithm. The list must be sorted into ascending order
* according to the {@linkplain Comparable natural ordering} of its
* elements (as by the {@link #sort(List)} method) prior to making this
* call. If it is not sorted, the results are undefined. If the list
* contains multiple elements equal to the specified object, there is no
* guarantee which one will be found.
*
* <p>This method runs in log(n) time for a "random access" list (which
* provides near-constant-time positional access). If the specified list
* does not implement the {@link RandomAccess} interface and is large,
* this method will do an iterator-based binary search that performs
* O(n) link traversals and O(log n) element comparisons.
*
* @param <T> the class of the objects in the list
* @param list the list to be searched.
* @param key the key to be searched for.
*
* @return the index of the search key, if it is contained in the list;
* otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The
* <i>insertion point</i> is defined as the point at which the
* key would be inserted into the list: the index of the first
* element greater than the key, or {@code list.size()} if all
* elements in the list are less than the specified key. Note
* that this guarantees that the return value will be >= 0 if
* and only if the key is found.
*
* @throws ClassCastException if the list contains elements that are not
* <i>mutually comparable</i> (for example, strings and
* integers), or the search key is not mutually comparable
* with the elements of the list.
*/
// 二分查找(使用内部比较器):在list中查找key,返回其索引
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) {
if(list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) {
return Collections.indexedBinarySearch(list, key);
} else {
return Collections.iteratorBinarySearch(list, key);
}
}
/**
* Searches the specified list for the specified object using the binary
* search algorithm. The list must be sorted into ascending order
* according to the specified comparator (as by the
* {@link #sort(List, Comparator) sort(List, Comparator)}
* method), prior to making this call. If it is
* not sorted, the results are undefined. If the list contains multiple
* elements equal to the specified object, there is no guarantee which one
* will be found.
*
* <p>This method runs in log(n) time for a "random access" list (which
* provides near-constant-time positional access). If the specified list
* does not implement the {@link RandomAccess} interface and is large,
* this method will do an iterator-based binary search that performs
* O(n) link traversals and O(log n) element comparisons.
*
* @param <T> the class of the objects in the list
* @param list the list to be searched.
* @param key the key to be searched for.
* @param c the comparator by which the list is ordered.
* A {@code null} value indicates that the elements'
* {@linkplain Comparable natural ordering} should be used.
*
* @return the index of the search key, if it is contained in the list;
* otherwise, <code>(-(<i>insertion point</i>) - 1)</code>. The
* <i>insertion point</i> is defined as the point at which the
* key would be inserted into the list: the index of the first
* element greater than the key, or {@code list.size()} if all
* elements in the list are less than the specified key. Note
* that this guarantees that the return value will be >= 0 if
* and only if the key is found.
*
* @throws ClassCastException if the list contains elements that are not
* <i>mutually comparable</i> using the specified comparator,
* or the search key is not mutually comparable with the
* elements of the list using this comparator.
*/
// 二分查找(使用外部比较器):在list中查找key,返回其索引
@SuppressWarnings("unchecked")
public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) {
if(c == null) {
return binarySearch((List<? extends Comparable<? super T>>) list, key);
}
if(list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) {
return Collections.indexedBinarySearch(list, key, c);
} else {
return Collections.iteratorBinarySearch(list, key, c);
}
}
/**
* Reverses the order of the elements in the specified list.<p>
*
* This method runs in linear time.
*
* @param list the list whose elements are to be reversed.
*
* @throws UnsupportedOperationException if the specified list or
* its list-iterator does not support the {@code set} operation.
*/
// 逆转list中的元素
@SuppressWarnings({"rawtypes", "unchecked"})
public static void reverse(List<?> list) {
int size = list.size();
if(size<REVERSE_THRESHOLD || list instanceof RandomAccess) {
for(int i = 0, mid = size >> 1, j = size - 1; i<mid; i++, j--) {
// 交换list中i和j的处的元素
swap(list, i, j);
}
} else {
/* instead of using a raw type here, it's possible to capture the wildcard but it will require a call to a supplementary private method */
ListIterator fwd = list.listIterator();
ListIterator rev = list.listIterator(size);
for(int i = 0, mid = list.size() >> 1; i<mid; i++) {
Object tmp = fwd.next();
fwd.set(rev.previous());
rev.set(tmp);
}
}
}
/**
* Rotates the elements in the specified list by the specified distance.
* After calling this method, the element at index {@code i} will be
* the element previously at index {@code (i - distance)} mod
* {@code list.size()}, for all values of {@code i} between {@code 0}
* and {@code list.size()-1}, inclusive. (This method has no effect on
* the size of the list.)
*
* <p>For example, suppose {@code list} comprises{@code [t, a, n, k, s]}.
* After invoking {@code Collections.rotate(list, 1)} (or
* {@code Collections.rotate(list, -4)}), {@code list} will comprise
* {@code [s, t, a, n, k]}.
*
* <p>Note that this method can usefully be applied to sublists to
* move one or more elements within a list while preserving the
* order of the remaining elements. For example, the following idiom
* moves the element at index {@code j} forward to position
* {@code k} (which must be greater than or equal to {@code j}):
* <pre>
* Collections.rotate(list.subList(j, k+1), -1);
* </pre>
* To make this concrete, suppose {@code list} comprises
* {@code [a, b, c, d, e]}. To move the element at index {@code 1}
* ({@code b}) forward two positions, perform the following invocation:
* <pre>
* Collections.rotate(l.subList(1, 4), -1);
* </pre>
* The resulting list is {@code [a, c, d, b, e]}.
*
* <p>To move more than one element forward, increase the absolute value
* of the rotation distance. To move elements backward, use a positive
* shift distance.
*
* <p>If the specified list is small or implements the {@link
* RandomAccess} interface, this implementation exchanges the first
* element into the location it should go, and then repeatedly exchanges
* the displaced element into the location it should go until a displaced
* element is swapped into the first element. If necessary, the process
* is repeated on the second and successive elements, until the rotation
* is complete. If the specified list is large and doesn't implement the
* {@code RandomAccess} interface, this implementation breaks the
* list into two sublist views around index {@code -distance mod size}.
* Then the {@link #reverse(List)} method is invoked on each sublist view,
* and finally it is invoked on the entire list. For a more complete
* description of both algorithms, see Section 2.3 of Jon Bentley's
* <i>Programming Pearls</i> (Addison-Wesley, 1986).
*
* @param list the list to be rotated.
* @param distance the distance to rotate the list. There are no
* constraints on this value; it may be zero, negative, or
* greater than {@code list.size()}.
*
* @throws UnsupportedOperationException if the specified list or
* its list-iterator does not support the {@code set} operation.
* @since 1.4
*/
/*
* 旋转list(包括内部的逆转)
* distance>0时,指示旋转之后左边子视图的长度
* distance<0时,指示旋转之后右边子视图的长度
*/
public static void rotate(List<?> list, int distance) {
if(list instanceof RandomAccess || list.size()<ROTATE_THRESHOLD) {
rotate1(list, distance);
} else {
rotate2(list, distance);
}
}
/**
* Randomly permutes the specified list using a default source of
* randomness. All permutations occur with approximately equal
* likelihood.
*
* <p>The hedge "approximately" is used in the foregoing description because
* default source of randomness is only approximately an unbiased source
* of independently chosen bits. If it were a perfect source of randomly
* chosen bits, then the algorithm would choose permutations with perfect
* uniformity.
*
* <p>This implementation traverses the list backwards, from the last
* element up to the second, repeatedly swapping a randomly selected element
* into the "current position". Elements are randomly selected from the
* portion of the list that runs from the first element to the current
* position, inclusive.
*
* <p>This method runs in linear time. If the specified list does not
* implement the {@link RandomAccess} interface and is large, this
* implementation dumps the specified list into an array before shuffling
* it, and dumps the shuffled array back into the list. This avoids the
* quadratic behavior that would result from shuffling a "sequential
* access" list in place.
*
* @param list the list to be shuffled.
*
* @throws UnsupportedOperationException if the specified list or
* its list-iterator does not support the {@code set} operation.
*/
// 随机排序list
public static void shuffle(List<?> list) {
Random rnd = r;
if(rnd == null) {
r = rnd = new Random(); // harmless race.
}
shuffle(list, rnd);
}
/**
* Randomly permute the specified list using the specified source of
* randomness. All permutations occur with equal likelihood
* assuming that the source of randomness is fair.<p>
*
* This implementation traverses the list backwards, from the last element
* up to the second, repeatedly swapping a randomly selected element into
* the "current position". Elements are randomly selected from the
* portion of the list that runs from the first element to the current
* position, inclusive.<p>
*
* This method runs in linear time. If the specified list does not
* implement the {@link RandomAccess} interface and is large, this
* implementation dumps the specified list into an array before shuffling
* it, and dumps the shuffled array back into the list. This avoids the
* quadratic behavior that would result from shuffling a "sequential
* access" list in place.
*
* @param list the list to be shuffled.
* @param rnd the source of randomness to use to shuffle the list.
*
* @throws UnsupportedOperationException if the specified list or its
* list-iterator does not support the {@code set} operation.
*/
// 随机排序list,伪随机数生成器由rnd给出
@SuppressWarnings({"rawtypes", "unchecked"})
public static void shuffle(List<?> list, Random rnd) {
int size = list.size();
if(size<SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
for(int i = size; i>1; i--) {
swap(list, i - 1, rnd.nextInt(i));
}
} else {
Object[] arr = list.toArray();
// Shuffle array
for(int i = size; i>1; i--) {
swap(arr, i - 1, rnd.nextInt(i));
}
/*
* Dump array back into list
* instead of using a raw type here, it's possible to capture the wildcard but it will require a call to a supplementary private method
*/
ListIterator it = list.listIterator();
for(Object e : arr) {
it.next();
it.set(e);
}
}
}
/**
* Swaps the elements at the specified positions in the specified list.
* (If the specified positions are equal, invoking this method leaves
* the list unchanged.)
*
* @param list The list in which to swap elements.
* @param i the index of one element to be swapped.
* @param j the index of the other element to be swapped.
*
* @throws IndexOutOfBoundsException if either {@code i} or {@code j}
* is out of range (i < 0 || i >= list.size()
* || j < 0 || j >= list.size()).
* @since 1.4
*/
// 交换list中i和j的处的元素
@SuppressWarnings({"rawtypes", "unchecked"})
public static void swap(List<?> list, int i, int j) {
/* instead of using a raw type here, it's possible to capture the wildcard but it will require a call to a supplementary private method */
final List l = list;
l.set(i, l.set(j, l.get(i)));
}
/**
* Replaces all of the elements of the specified list with the specified
* element. <p>
*
* This method runs in linear time.
*
* @param <T> the class of the objects in the list
* @param list the list to be filled with the specified element.
* @param obj The element with which to fill the specified list.
*
* @throws UnsupportedOperationException if the specified list or its
* list-iterator does not support the {@code set} operation.
*/
// 使用指定的元素obj来填充list
public static <T> void fill(List<? super T> list, T obj) {
int size = list.size();
if(size<FILL_THRESHOLD || list instanceof RandomAccess) {
for(int i = 0; i<size; i++) {
list.set(i, obj);
}
} else {
ListIterator<? super T> itr = list.listIterator();
for(int i = 0; i<size; i++) {
itr.next();
itr.set(obj);
}
}
}
/**
* Replaces all occurrences of one specified value in a list with another.
* More formally, replaces with {@code newVal} each element {@code e}
* in {@code list} such that
* {@code (oldVal==null ? e==null : oldVal.equals(e))}.
* (This method has no effect on the size of the list.)
*
* @param <T> the class of the objects in the list
* @param list the list in which replacement is to occur.
* @param oldVal the old value to be replaced.
* @param newVal the new value with which {@code oldVal} is to be
* replaced.
*
* @return {@code true} if {@code list} contained one or more elements
* {@code e} such that
* {@code (oldVal==null ? e==null : oldVal.equals(e))}.
*
* @throws UnsupportedOperationException if the specified list or
* its list-iterator does not support the {@code set} operation.
* @since 1.4
*/
// 将list中所有oldVal替换为newVal
public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {
boolean result = false;
int size = list.size();
if(size<REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
if(oldVal == null) {
for(int i = 0; i<size; i++) {
if(list.get(i) == null) {
list.set(i, newVal);
result = true;
}
}
} else {
for(int i = 0; i<size; i++) {
if(oldVal.equals(list.get(i))) {
list.set(i, newVal);
result = true;
}
}
}
} else {
ListIterator<T> itr = list.listIterator();
if(oldVal == null) {
for(int i = 0; i<size; i++) {
if(itr.next() == null) {
itr.set(newVal);
result = true;
}
}
} else {
for(int i = 0; i<size; i++) {
if(oldVal.equals(itr.next())) {
itr.set(newVal);
result = true;
}
}
}
}
return result;
}
/**
* Copies all of the elements from one list into another. After the
* operation, the index of each copied element in the destination list
* will be identical to its index in the source list. The destination
* list's size must be greater than or equal to the source list's size.
* If it is greater, the remaining elements in the destination list are
* unaffected. <p>
*
* This method runs in linear time.
*
* @param <T> the class of the objects in the lists
* @param dest The destination list.
* @param src The source list.
*
* @throws IndexOutOfBoundsException if the destination list is too small
* to contain the entire source List.
* @throws UnsupportedOperationException if the destination list's
* list-iterator does not support the {@code set} operation.
*/
// 将dest中的元素拷贝到src中(浅拷贝)
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
int srcSize = src.size();
if(srcSize>dest.size()) {
throw new IndexOutOfBoundsException("Source does not fit in dest");
}
if(srcSize<COPY_THRESHOLD || (src instanceof RandomAccess && dest instanceof RandomAccess)) {
for(int i = 0; i<srcSize; i++) {
dest.set(i, src.get(i));
}
} else {
ListIterator<? super T> di = dest.listIterator();
ListIterator<? extends T> si = src.listIterator();
for(int i = 0; i<srcSize; i++) {
di.next();
di.set(si.next());
}
}
}
/**
* Returns the minimum element of the given collection, according to the
* <i>natural ordering</i> of its elements. All elements in the
* collection must implement the {@code Comparable} interface.
* Furthermore, all elements in the collection must be <i>mutually
* comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the collection).<p>
*
* This method iterates over the entire collection, hence it requires
* time proportional to the size of the collection.
*
* @param <T> the class of the objects in the collection
* @param coll the collection whose minimum element is to be determined.
*
* @return the minimum element of the given collection, according
* to the <i>natural ordering</i> of its elements.
*
* @throws ClassCastException if the collection contains elements that are
* not <i>mutually comparable</i> (for example, strings and
* integers).
* @throws NoSuchElementException if the collection is empty.
* @see Comparable
*/
// 返回指定容器中最小的元素(使用内部比较器比较大小)
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while(i.hasNext()) {
T next = i.next();
if(next.compareTo(candidate)<0) {
candidate = next;
}
}
return candidate;
}
/**
* Returns the minimum element of the given collection, according to the
* order induced by the specified comparator. All elements in the
* collection must be <i>mutually comparable</i> by the specified
* comparator (that is, {@code comp.compare(e1, e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the collection).<p>
*
* This method iterates over the entire collection, hence it requires
* time proportional to the size of the collection.
*
* @param <T> the class of the objects in the collection
* @param coll the collection whose minimum element is to be determined.
* @param comp the comparator with which to determine the minimum element.
* A {@code null} value indicates that the elements' <i>natural
* ordering</i> should be used.
*
* @return the minimum element of the given collection, according
* to the specified comparator.
*
* @throws ClassCastException if the collection contains elements that are
* not <i>mutually comparable</i> using the specified comparator.
* @throws NoSuchElementException if the collection is empty.
* @see Comparable
*/
// 返回指定容器中最小的元素(使用外部比较器比较大小)
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
if(comp == null) {
return (T) min((Collection) coll);
}
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while(i.hasNext()) {
T next = i.next();
if(comp.compare(next, candidate)<0) {
candidate = next;
}
}
return candidate;
}
/**
* Returns the maximum element of the given collection, according to the
* <i>natural ordering</i> of its elements. All elements in the
* collection must implement the {@code Comparable} interface.
* Furthermore, all elements in the collection must be <i>mutually
* comparable</i> (that is, {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the collection).<p>
*
* This method iterates over the entire collection, hence it requires
* time proportional to the size of the collection.
*
* @param <T> the class of the objects in the collection
* @param coll the collection whose maximum element is to be determined.
*
* @return the maximum element of the given collection, according
* to the <i>natural ordering</i> of its elements.
*
* @throws ClassCastException if the collection contains elements that are
* not <i>mutually comparable</i> (for example, strings and
* integers).
* @throws NoSuchElementException if the collection is empty.
* @see Comparable
*/
// 返回指定容器中最大的元素(使用内部比较器比较大小)
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while(i.hasNext()) {
T next = i.next();
if(next.compareTo(candidate)>0) {
candidate = next;
}
}
return candidate;
}
/**
* Returns the maximum element of the given collection, according to the
* order induced by the specified comparator. All elements in the
* collection must be <i>mutually comparable</i> by the specified
* comparator (that is, {@code comp.compare(e1, e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the collection).<p>
*
* This method iterates over the entire collection, hence it requires
* time proportional to the size of the collection.
*
* @param <T> the class of the objects in the collection
* @param coll the collection whose maximum element is to be determined.
* @param comp the comparator with which to determine the maximum element.
* A {@code null} value indicates that the elements' <i>natural
* ordering</i> should be used.
*
* @return the maximum element of the given collection, according
* to the specified comparator.
*
* @throws ClassCastException if the collection contains elements that are
* not <i>mutually comparable</i> using the specified comparator.
* @throws NoSuchElementException if the collection is empty.
* @see Comparable
*/
// 返回指定容器中最大的元素(使用外部比较器比较大小)
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {
if(comp == null) {
return (T) max((Collection) coll);
}
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while(i.hasNext()) {
T next = i.next();
if(comp.compare(next, candidate)>0) {
candidate = next;
}
}
return candidate;
}
/**
* Returns the starting position of the first occurrence of the specified
* target list within the specified source list, or -1 if there is no
* such occurrence. More formally, returns the lowest index {@code i}
* such that {@code source.subList(i, i+target.size()).equals(target)},
* or -1 if there is no such index. (Returns -1 if
* {@code target.size() > source.size()})
*
* <p>This implementation uses the "brute force" technique of scanning
* over the source list, looking for a match with the target at each
* location in turn.
*
* @param source the list in which to search for the first occurrence of {@code target}.
* @param target the list to search for as a subList of {@code source}.
*
* @return the starting position of the first occurrence of the specified
* target list within the specified source list, or -1 if there
* is no such occurrence.
*
* @since 1.4
*/
// 查找子串target在主串source中的正序索引(正序查找)
public static int indexOfSubList(List<?> source, List<?> target) {
int sourceSize = source.size();
int targetSize = target.size();
int maxCandidate = sourceSize - targetSize;
if(sourceSize<INDEXOFSUBLIST_THRESHOLD || (source instanceof RandomAccess && target instanceof RandomAccess)) {
nextCand:
for(int candidate = 0; candidate<=maxCandidate; candidate++) {
for(int i = 0, j = candidate; i<targetSize; i++, j++) {
if(!eq(target.get(i), source.get(j))) {
continue nextCand; // Element mismatch, try next cand
}
}
return candidate; // All elements of candidate matched target
}
} else { // Iterator version of above algorithm
ListIterator<?> si = source.listIterator();
nextCand:
for(int candidate = 0; candidate<=maxCandidate; candidate++) {
ListIterator<?> ti = target.listIterator();
for(int i = 0; i<targetSize; i++) {
if(!eq(ti.next(), si.next())) {
// Back up source iterator to next candidate
for(int j = 0; j<i; j++) {
si.previous();
}
continue nextCand;
}
}
return candidate;
}
}
return -1; // No candidate matched the target
}
/**
* Returns the starting position of the last occurrence of the specified
* target list within the specified source list, or -1 if there is no such
* occurrence. More formally, returns the highest index {@code i}
* such that {@code source.subList(i, i+target.size()).equals(target)},
* or -1 if there is no such index. (Returns -1 if
* {@code target.size() > source.size()})
*
* <p>This implementation uses the "brute force" technique of iterating
* over the source list, looking for a match with the target at each
* location in turn.
*
* @param source the list in which to search for the last occurrence
* of {@code target}.
* @param target the list to search for as a subList of {@code source}.
*
* @return the starting position of the last occurrence of the specified
* target list within the specified source list, or -1 if there
* is no such occurrence.
*
* @since 1.4
*/
// 查找子串target在主串source中的逆序索引(逆序查找)
public static int lastIndexOfSubList(List<?> source, List<?> target) {
int sourceSize = source.size();
int targetSize = target.size();
int maxCandidate = sourceSize - targetSize;
if(sourceSize<INDEXOFSUBLIST_THRESHOLD || source instanceof RandomAccess) { // Index access version
nextCand:
for(int candidate = maxCandidate; candidate >= 0; candidate--) {
for(int i = 0, j = candidate; i<targetSize; i++, j++) {
if(!eq(target.get(i), source.get(j))) {
continue nextCand; // Element mismatch, try next cand
}
}
return candidate; // All elements of candidate matched target
}
} else { // Iterator version of above algorithm
if(maxCandidate<0) {
return -1;
}
ListIterator<?> si = source.listIterator(maxCandidate);
nextCand:
for(int candidate = maxCandidate; candidate >= 0; candidate--) {
ListIterator<?> ti = target.listIterator();
for(int i = 0; i<targetSize; i++) {
if(!eq(ti.next(), si.next())) {
if(candidate != 0) {
// Back up source iterator to next candidate
for(int j = 0; j<=i + 1; j++) {
si.previous();
}
}
continue nextCand;
}
}
return candidate;
}
}
return -1; // No candidate matched the target
}
/*▲ List操作 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 只读容器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
* specified collection. Query operations on the returned collection "read through"
* to the specified collection, and attempts to modify the returned
* collection, whether direct or via its iterator, result in an
* {@code UnsupportedOperationException}.<p>
*
* The returned collection does <i>not</i> pass the hashCode and equals
* operations through to the backing collection, but relies on
* {@code Object}'s {@code equals} and {@code hashCode} methods. This
* is necessary to preserve the contracts of these operations in the case
* that the backing collection is a set or a list.<p>
*
* The returned collection will be serializable if the specified collection
* is serializable.
*
* @param <T> the class of the objects in the collection
* @param c the collection for which an unmodifiable view is to be
* returned.
*
* @return an unmodifiable view of the specified collection.
*/
// 将指定的容器包装为只读容器
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
return new UnmodifiableCollection<>(c);
}
/**
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
* specified set. Query operations on the returned set "read through" to the specified
* set, and attempts to modify the returned set, whether direct or via its
* iterator, result in an {@code UnsupportedOperationException}.<p>
*
* The returned set will be serializable if the specified set
* is serializable.
*
* @param <T> the class of the objects in the set
* @param s the set for which an unmodifiable view is to be returned.
*
* @return an unmodifiable view of the specified set.
*/
// 将指定的Set包装为只读Set
public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
return new UnmodifiableSet<>(s);
}
/**
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
* specified sorted set. Query operations on the returned sorted set "read
* through" to the specified sorted set. Attempts to modify the returned
* sorted set, whether direct, via its iterator, or via its
* {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
* an {@code UnsupportedOperationException}.<p>
*
* The returned sorted set will be serializable if the specified sorted set
* is serializable.
*
* @param <T> the class of the objects in the set
* @param s the sorted set for which an unmodifiable view is to be
* returned.
*
* @return an unmodifiable view of the specified sorted set.
*/
// 将指定的Set包装为只读Set
public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
return new UnmodifiableSortedSet<>(s);
}
/**
* Returns an <a href="Collection.html#unmodview">unmodifiable view</a> of the
* specified navigable set. Query operations on the returned navigable set "read
* through" to the specified navigable set. Attempts to modify the returned
* navigable set, whether direct, via its iterator, or via its
* {@code subSet}, {@code headSet}, or {@code tailSet} views, result in
* an {@code UnsupportedOperationException}.<p>