forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BitSet.java
1702 lines (1452 loc) · 60.3 KB
/
BitSet.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) 1995, 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.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.LongBuffer;
import java.util.function.IntConsumer;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
/**
* This class implements a vector of bits that grows as needed. Each
* component of the bit set has a {@code boolean} value. The
* bits of a {@code BitSet} are indexed by nonnegative integers.
* Individual indexed bits can be examined, set, or cleared. One
* {@code BitSet} may be used to modify the contents of another
* {@code BitSet} through logical AND, logical inclusive OR, and
* logical exclusive OR operations.
*
* <p>By default, all bits in the set initially have the value
* {@code false}.
*
* <p>Every bit set has a current size, which is the number of bits
* of space currently in use by the bit set. Note that the size is
* related to the implementation of a bit set, so it may change with
* implementation. The length of a bit set relates to logical length
* of a bit set and is defined independently of implementation.
*
* <p>Unless otherwise noted, passing a null parameter to any of the
* methods in a {@code BitSet} will result in a
* {@code NullPointerException}.
*
* <p>A {@code BitSet} is not safe for multithreaded use without
* external synchronization.
*
* @author Arthur van Hoff
* @author Michael McCloskey
* @author Martin Buchholz
* @since 1.0
*/
/*
* 位集
*
* 位集中的元素是单个二进制位。
* 对于在海量数据中判断某个数据的存在性问题,使用位集可以节省空间。
*/
public class BitSet implements Cloneable, Serializable {
/*
* BitSets are packed into arrays of "words." Currently a word is
* a long, which consists of 64 bits, requiring 6 address bits.
* The choice of word size is determined purely by performance concerns.
*/
private static final int ADDRESS_BITS_PER_WORD = 6;
// 每个word所占的位数:64bit,(这里所谓的word就是long)
private static final int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD;
private static final int BIT_INDEX_MASK = BITS_PER_WORD - 1;
/* Used to shift left or right for a partial word mask */
private static final long WORD_MASK = 0xffffffffffffffffL;
/**
* The internal field corresponding to the serialField "bits".
*/
/*
* 存储word,其实就是存储位集中的bit
* 在计算位的时候,需要从左到右取出word,并从右到左排列。
*/
private long[] words;
/**
* The number of words in the logical size of this BitSet.
*/
// 位集正在被使用的字的长度
private transient int wordsInUse = 0;
/**
* Whether the size of "words" is user-specified. If so, we assume
* the user knows what he's doing and try harder to preserve it.
*/
// 字的大小是否为用户指定
private transient boolean sizeIsSticky = false;
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates a new bit set. All bits are initially {@code false}.
*/
// 构造可以存储64个bit的位集(即1个word)
public BitSet() {
// 由给定的bit数量,构造一个匹配大小的long数组存储bit
initWords(BITS_PER_WORD);
sizeIsSticky = false;
}
/**
* Creates a bit set whose initial size is large enough to explicitly
* represent bits with indices in the range {@code 0} through
* {@code nbits-1}. All bits are initially {@code false}.
*
* @param nbits the initial size of the bit set
*
* @throws NegativeArraySizeException if the specified initial size
* is negative
*/
// 构造至少可以存储nbits个bit的位集
public BitSet(int nbits) {
// nbits can't be negative; size 0 is OK
if(nbits<0) {
throw new NegativeArraySizeException("nbits < 0: " + nbits);
}
// 由给定的bit数量,构造一个匹配大小的long数组存储bit
initWords(nbits);
sizeIsSticky = true;
}
/**
* Creates a bit set using words as the internal representation.
* The last word (if there is one) must be non-zero.
*/
// 构造可以存储words.length个word的位集,且该位集正在被使用
private BitSet(long[] words) {
this.words = words;
this.wordsInUse = words.length;
checkInvariants();
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 工厂方法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a new bit set containing all the bits in the given long array.
*
* <p>More precisely,
* <br>{@code BitSet.valueOf(longs).get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}
* <br>for all {@code n < 64 * longs.length}.
*
* <p>This method is equivalent to
* {@code BitSet.valueOf(LongBuffer.wrap(longs))}.
*
* @param longs a long array containing a little-endian representation
* of a sequence of bits to be used as the initial bits of the
* new bit set
*
* @return a {@code BitSet} containing all the bits in the long array
*
* @since 1.7
*/
/*
* 用指定的long数组构造位集
*
* 从后向前遍历数组longs,丢弃遇到的值为0的元素,直到遇到首个不为0的元素后,将该元素以及之前的元素保存到位集中。
*/
public static BitSet valueOf(long[] longs) {
int n;
// 从后向前遍历,丢弃0元素,直到遇到首个非0元素
for(n = longs.length; n>0 && longs[n - 1] == 0; n--)
;
return new BitSet(Arrays.copyOf(longs, n));
}
/**
* Returns a new bit set containing all the bits in the given long
* buffer between its position and limit.
*
* <p>More precisely,
* <br>{@code BitSet.valueOf(lb).get(n) == ((lb.get(lb.position()+n/64) & (1L<<(n%64))) != 0)}
* <br>for all {@code n < 64 * lb.remaining()}.
*
* <p>The long buffer is not modified by this method, and no
* reference to the buffer is retained by the bit set.
*
* @param lb a long buffer containing a little-endian representation
* of a sequence of bits between its position and limit, to be
* used as the initial bits of the new bit set
*
* @return a {@code BitSet} containing all the bits in the buffer in the
* specified range
*
* @since 1.7
*/
/*
* 用指定的long缓冲区构造位集
*
* 从后向前遍历缓冲区lb,丢弃遇到的值为0的元素,直到遇到首个不为0的元素后,将该元素以及之前的元素保存到位集中。
*/
public static BitSet valueOf(LongBuffer lb) {
lb = lb.slice();
int n;
// 从后向前遍历,丢弃0元素,直到遇到首个非0元素
for(n = lb.remaining(); n>0 && lb.get(n - 1) == 0; n--)
;
long[] words = new long[n];
lb.get(words);
return new BitSet(words);
}
/**
* Returns a new bit set containing all the bits in the given byte array.
*
* <p>More precisely,
* <br>{@code BitSet.valueOf(bytes).get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}
* <br>for all {@code n < 8 * bytes.length}.
*
* <p>This method is equivalent to
* {@code BitSet.valueOf(ByteBuffer.wrap(bytes))}.
*
* @param bytes a byte array containing a little-endian
* representation of a sequence of bits to be used as the
* initial bits of the new bit set
*
* @return a {@code BitSet} containing all the bits in the byte array
*
* @since 1.7
*/
/*
* 用指定的bytes数组构造位集
*
* 从后向前遍历数组bytes,丢弃遇到的值为0的元素,直到遇到首个不为0的元素后,将该元素以及之前的元素保存到位集中。
*/
public static BitSet valueOf(byte[] bytes) {
return BitSet.valueOf(ByteBuffer.wrap(bytes));
}
/**
* Returns a new bit set containing all the bits in the given byte
* buffer between its position and limit.
*
* <p>More precisely,
* <br>{@code BitSet.valueOf(bb).get(n) == ((bb.get(bb.position()+n/8) & (1<<(n%8))) != 0)}
* <br>for all {@code n < 8 * bb.remaining()}.
*
* <p>The byte buffer is not modified by this method, and no
* reference to the buffer is retained by the bit set.
*
* @param bb a byte buffer containing a little-endian representation
* of a sequence of bits between its position and limit, to be
* used as the initial bits of the new bit set
*
* @return a {@code BitSet} containing all the bits in the buffer in the
* specified range
*
* @since 1.7
*/
/*
* 用指定的byte缓冲区构造位集
*
* 从后向前遍历缓冲区bb,丢弃遇到的值为0的元素,直到遇到首个不为0的元素后,将该元素以及之前的元素保存到位集中。
*/
public static BitSet valueOf(ByteBuffer bb) {
bb = bb.slice().order(ByteOrder.LITTLE_ENDIAN);
int n;
// 从后向前遍历,丢弃0元素,直到遇到首个非0元素
for(n = bb.remaining(); n>0 && bb.get(n - 1) == 0; n--)
;
long[] words = new long[(n + 7) / 8];
bb.limit(n);
int i = 0;
while(bb.remaining() >= 8) {
// 一次读8个字节,按long解析,将position增加8个单位
words[i++] = bb.getLong();
}
for(int remaining = bb.remaining(), j = 0; j<remaining; j++) {
words[i] |= (bb.get() & 0xffL) << (8 * j);
}
return new BitSet(words);
}
/*▲ 工厂方法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 数组化 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a new long array containing all the bits in this bit set.
*
* <p>More precisely, if
* <br>{@code long[] longs = s.toLongArray();}
* <br>then {@code longs.length == (s.length()+63)/64} and
* <br>{@code s.get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}
* <br>for all {@code n < 64 * longs.length}.
*
* @return a long array containing a little-endian representation
* of all the bits in this bit set
*
* @since 1.7
*/
// 以long数组形式返回位集中的数据
public long[] toLongArray() {
return Arrays.copyOf(words, wordsInUse);
}
/**
* Returns a new byte array containing all the bits in this bit set.
*
* <p>More precisely, if
* <br>{@code byte[] bytes = s.toByteArray();}
* <br>then {@code bytes.length == (s.length()+7)/8} and
* <br>{@code s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}
* <br>for all {@code n < 8 * bytes.length}.
*
* @return a byte array containing a little-endian representation
* of all the bits in this bit set
*
* @since 1.7
*/
// 以byte数组形式返回位集中的数据
public byte[] toByteArray() {
int n = wordsInUse;
if(n == 0) {
return new byte[0];
}
int len = 8 * (n - 1);
for(long x = words[n - 1]; x != 0; x >>>= 8) {
len++;
}
byte[] bytes = new byte[len];
ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
for(int i = 0; i<n - 1; i++) {
bb.putLong(words[i]);
}
for(long x = words[n - 1]; x != 0; x >>>= 8) {
bb.put((byte) (x & 0xff));
}
return bytes;
}
/*▲ 数组化 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 获取/设置/清除 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the value of the bit with the specified index. The value
* is {@code true} if the bit with the index {@code bitIndex}
* is currently set in this {@code BitSet}; otherwise, the result
* is {@code false}.
*
* @param bitIndex the bit index
*
* @return the value of the bit with the specified index
*
* @throws IndexOutOfBoundsException if the specified index is negative
*/
// 判断bitIndex处的bit是否为1(bitIndex需要从右往左计数)
public boolean get(int bitIndex) {
if(bitIndex<0) {
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
}
checkInvariants();
int wordIndex = wordIndex(bitIndex);
return (wordIndex<wordsInUse) && ((words[wordIndex] & (1L << bitIndex)) != 0);
}
/**
* Returns a new {@code BitSet} composed of bits from this {@code BitSet}
* from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive).
*
* @param fromIndex index of the first bit to include
* @param toIndex index after the last bit to include
*
* @return a new {@code BitSet} from a range of this {@code BitSet}
*
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
* or {@code toIndex} is negative, or {@code fromIndex} is
* larger than {@code toIndex}
* @since 1.4
*/
// 返回一个子位集,其包含原位集[fromIndex, toIndex)范围内的数据
public BitSet get(int fromIndex, int toIndex) {
checkRange(fromIndex, toIndex);
checkInvariants();
int len = length();
// If no set bits in range return empty bitset
if(len<=fromIndex || fromIndex == toIndex) {
return new BitSet(0);
}
// An optimization
if(toIndex>len) {
toIndex = len;
}
BitSet result = new BitSet(toIndex - fromIndex);
int targetWords = wordIndex(toIndex - fromIndex - 1) + 1;
int sourceIndex = wordIndex(fromIndex);
boolean wordAligned = ((fromIndex & BIT_INDEX_MASK) == 0);
// Process all words but the last word
for(int i = 0; i<targetWords - 1; i++, sourceIndex++) {
result.words[i] = wordAligned ? words[sourceIndex] : (words[sourceIndex] >>> fromIndex) | (words[sourceIndex + 1] << -fromIndex);
}
// Process the last word
long lastWordMask = WORD_MASK >>> -toIndex;
/* straddles source words */
result.words[targetWords - 1] = ((toIndex - 1) & BIT_INDEX_MASK)<(fromIndex & BIT_INDEX_MASK) ? ((words[sourceIndex] >>> fromIndex) | (words[sourceIndex + 1] & lastWordMask) << -fromIndex) : ((words[sourceIndex] & lastWordMask) >>> fromIndex);
// Set wordsInUse correctly
result.wordsInUse = targetWords;
result.recalculateWordsInUse();
result.checkInvariants();
return result;
}
/**
* Sets the bit at the specified index to the specified value.
*
* @param bitIndex a bit index
* @param value a boolean value to set
*
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
/*
* 对指定索引处的bit进行设置/清除
*
* bitIndex: bit索引,从右往左计数
* value : 设置(true)还是清除(false)
*/
public void set(int bitIndex, boolean value) {
if(value) {
set(bitIndex);
} else {
clear(bitIndex);
}
}
/**
* Sets the bit at the specified index to {@code true}.
*
* @param bitIndex a bit index
*
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.0
*/
/*
* 将位集中指定索引处的bit设置为1。
* 注:索引是从右往左计数的。
*/
public void set(int bitIndex) {
if(bitIndex<0) {
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
}
// 计算指定索引处的bit所在的word的索引
int wordIndex = wordIndex(bitIndex);
// 尝试扩容位集,使其足够存放wordIndex + 1个bit
expandTo(wordIndex);
// 设置bit
words[wordIndex] |= (1L << bitIndex); // Restores invariants
checkInvariants();
}
/**
* Sets the bit specified by the index to {@code false}.
*
* @param bitIndex the index of the bit to be cleared
*
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.0
*/
/*
* 将位集中指定索引处的bit设置为0。
* 注:索引是从右往左计数的。
*/
public void clear(int bitIndex) {
if(bitIndex<0) {
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
}
// 计算指定索引处的bit所在的word的索引
int wordIndex = wordIndex(bitIndex);
// 如果越界,直接返回
if(wordIndex >= wordsInUse) {
return;
}
// 清除bit
words[wordIndex] &= ~(1L << bitIndex);
// 重新计算使用的word的数量
recalculateWordsInUse();
checkInvariants();
}
/**
* Sets the bits from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to the specified value.
*
* @param fromIndex index of the first bit to be set
* @param toIndex index after the last bit to be set
* @param value value to set the selected bits to
*
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
* or {@code toIndex} is negative, or {@code fromIndex} is
* larger than {@code toIndex}
* @since 1.4
*/
/*
* 对[fromIndex, toIndex)处的bit进行批量设置/清除
*
* bitIndex: bit索引,从右往左计数
* value : 设置(true)还是清除(false)
*/
public void set(int fromIndex, int toIndex, boolean value) {
if(value) {
set(fromIndex, toIndex);
} else {
clear(fromIndex, toIndex);
}
}
/**
* Sets the bits from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to {@code true}.
*
* @param fromIndex index of the first bit to be set
* @param toIndex index after the last bit to be set
*
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
* or {@code toIndex} is negative, or {@code fromIndex} is
* larger than {@code toIndex}
* @since 1.4
*/
/*
* 将[fromIndex, toIndex)处的bit批量设置为1。
* 注:索引是从右往左计数的。
*/
public void set(int fromIndex, int toIndex) {
checkRange(fromIndex, toIndex);
if(fromIndex == toIndex) {
return;
}
// Increase capacity if necessary
int startWordIndex = wordIndex(fromIndex);
int endWordIndex = wordIndex(toIndex - 1);
// 尝试扩容位集,使其足够存放wordIndex + 1个bit
expandTo(endWordIndex);
long firstWordMask = WORD_MASK << fromIndex;
long lastWordMask = WORD_MASK >>> -toIndex;
if(startWordIndex == endWordIndex) {
// Case 1: One word
words[startWordIndex] |= (firstWordMask & lastWordMask);
} else {
// Case 2: Multiple words
// Handle first word
words[startWordIndex] |= firstWordMask;
// Handle intermediate words, if any
for(int i = startWordIndex + 1; i<endWordIndex; i++)
words[i] = WORD_MASK;
// Handle last word (restores invariants)
words[endWordIndex] |= lastWordMask;
}
checkInvariants();
}
/**
* Sets the bits from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to {@code false}.
*
* @param fromIndex index of the first bit to be cleared
* @param toIndex index after the last bit to be cleared
*
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
* or {@code toIndex} is negative, or {@code fromIndex} is
* larger than {@code toIndex}
* @since 1.4
*/
/*
* 将[fromIndex, toIndex)处的bit批量设置为0。
* 注:索引是从右往左计数的。
*/
public void clear(int fromIndex, int toIndex) {
checkRange(fromIndex, toIndex);
if(fromIndex == toIndex) {
return;
}
int startWordIndex = wordIndex(fromIndex);
if(startWordIndex >= wordsInUse) {
return;
}
int endWordIndex = wordIndex(toIndex - 1);
if(endWordIndex >= wordsInUse) {
toIndex = length();
endWordIndex = wordsInUse - 1;
}
long firstWordMask = WORD_MASK << fromIndex;
long lastWordMask = WORD_MASK >>> -toIndex;
if(startWordIndex == endWordIndex) {
// Case 1: One word
words[startWordIndex] &= ~(firstWordMask & lastWordMask);
} else {
// Case 2: Multiple words
// Handle first word
words[startWordIndex] &= ~firstWordMask;
// Handle intermediate words, if any
for(int i = startWordIndex + 1; i<endWordIndex; i++) {
words[i] = 0;
}
// Handle last word
words[endWordIndex] &= ~lastWordMask;
}
recalculateWordsInUse();
checkInvariants();
}
/**
* Sets all of the bits in this BitSet to {@code false}.
*
* @since 1.4
*/
// 清除所有的bit(都设置为0)
public void clear() {
while(wordsInUse>0) {
words[--wordsInUse] = 0;
}
}
/*▲ 获取/设置/清除 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 翻转 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Sets the bit at the specified index to the complement of its
* current value.
*
* @param bitIndex the index of the bit to flip
*
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
// 翻转指定索引处的bit,即从0到1,或从1到0(索引从右往左计数)
public void flip(int bitIndex) {
if(bitIndex<0) {
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
}
int wordIndex = wordIndex(bitIndex);
expandTo(wordIndex);
words[wordIndex] ^= (1L << bitIndex);
recalculateWordsInUse();
checkInvariants();
}
/**
* Sets each bit from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to the complement of its current
* value.
*
* @param fromIndex index of the first bit to flip
* @param toIndex index after the last bit to flip
*
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
* or {@code toIndex} is negative, or {@code fromIndex} is
* larger than {@code toIndex}
* @since 1.4
*/
// 翻转[fromIndex, toIndex)处的bit,即从0到1,或从1到0(索引从右往左计数)
public void flip(int fromIndex, int toIndex) {
checkRange(fromIndex, toIndex);
if(fromIndex == toIndex) {
return;
}
int startWordIndex = wordIndex(fromIndex);
int endWordIndex = wordIndex(toIndex - 1);
expandTo(endWordIndex);
long firstWordMask = WORD_MASK << fromIndex;
long lastWordMask = WORD_MASK >>> -toIndex;
if(startWordIndex == endWordIndex) {
// Case 1: One word
words[startWordIndex] ^= (firstWordMask & lastWordMask);
} else {
// Case 2: Multiple words
// Handle first word
words[startWordIndex] ^= firstWordMask;
// Handle intermediate words, if any
for(int i = startWordIndex + 1; i<endWordIndex; i++) {
words[i] ^= WORD_MASK;
}
// Handle last word
words[endWordIndex] ^= lastWordMask;
}
recalculateWordsInUse();
checkInvariants();
}
/*▲ 翻转 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 定位 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the index of the first bit that is set to {@code true}
* that occurs on or after the specified starting index. If no such
* bit exists then {@code -1} is returned.
*
* <p>To iterate over the {@code true} bits in a {@code BitSet},
* use the following loop:
*
* <pre> {@code
* for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
* // operate on index i here
* if (i == Integer.MAX_VALUE) {
* break; // or (i+1) would overflow
* }
* }}</pre>
*
* @param fromIndex the index to start checking from (inclusive)
*
* @return the index of the next set bit, or {@code -1} if there
* is no such bit
*
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
// 返回下一个值为1的bit索引,需要从fromIndex处开始,从右向左查找
public int nextSetBit(int fromIndex) {
if(fromIndex<0) {
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
}
checkInvariants();
int u = wordIndex(fromIndex);
if(u >= wordsInUse) {
return -1;
}
long word = words[u] & (WORD_MASK << fromIndex);
while(true) {
if(word != 0) {
return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
}
if(++u == wordsInUse) {
return -1;
}
word = words[u];
}
}
/**
* Returns the index of the first bit that is set to {@code false}
* that occurs on or after the specified starting index.
*
* @param fromIndex the index to start checking from (inclusive)
*
* @return the index of the next clear bit
*
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
// 返回下一个值为0的bit索引,需要从fromIndex处开始,从右向左查找
public int nextClearBit(int fromIndex) {
/*
* Neither spec nor implementation handle bitsets of maximal length.
* See 4816253.
*/
if(fromIndex<0) {
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
}
checkInvariants();
int u = wordIndex(fromIndex);
if(u >= wordsInUse)
return fromIndex;
long word = ~words[u] & (WORD_MASK << fromIndex);
while(true) {
if(word != 0) {
return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
}
if(++u == wordsInUse) {
return wordsInUse * BITS_PER_WORD;
}
word = ~words[u];
}
}
/**
* Returns the index of the nearest bit that is set to {@code true}
* that occurs on or before the specified starting index.
* If no such bit exists, or if {@code -1} is given as the
* starting index, then {@code -1} is returned.
*
* <p>To iterate over the {@code true} bits in a {@code BitSet},
* use the following loop:
*
* <pre> {@code
* for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {
* // operate on index i here
* }}</pre>
*
* @param fromIndex the index to start checking from (inclusive)
*
* @return the index of the previous set bit, or {@code -1} if there
* is no such bit
*
* @throws IndexOutOfBoundsException if the specified index is less
* than {@code -1}
* @since 1.7
*/
// 返回前一个值为1的bit索引,需要从fromIndex处开始,从左向右查找
public int previousSetBit(int fromIndex) {
if(fromIndex<0) {
if(fromIndex == -1) {
return -1;
}
throw new IndexOutOfBoundsException("fromIndex < -1: " + fromIndex);
}
checkInvariants();
int u = wordIndex(fromIndex);
if(u >= wordsInUse) {
return length() - 1;
}
long word = words[u] & (WORD_MASK >>> -(fromIndex + 1));
while(true) {
if(word != 0) {
return (u + 1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word);
}
if(u-- == 0) {
return -1;
}
word = words[u];
}
}
/**
* Returns the index of the nearest bit that is set to {@code false}
* that occurs on or before the specified starting index.
* If no such bit exists, or if {@code -1} is given as the
* starting index, then {@code -1} is returned.
*
* @param fromIndex the index to start checking from (inclusive)
*
* @return the index of the previous clear bit, or {@code -1} if there
* is no such bit
*
* @throws IndexOutOfBoundsException if the specified index is less
* than {@code -1}
* @since 1.7
*/
// 返回前一个值为0的bit索引,需要从fromIndex处开始,从左向右查找
public int previousClearBit(int fromIndex) {
if(fromIndex<0) {
if(fromIndex == -1) {
return -1;
}
throw new IndexOutOfBoundsException("fromIndex < -1: " + fromIndex);
}
checkInvariants();
int u = wordIndex(fromIndex);
if(u >= wordsInUse) {
return fromIndex;
}
long word = ~words[u] & (WORD_MASK >>> -(fromIndex + 1));
while(true) {
if(word != 0) {
return (u + 1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word);
}
if(u-- == 0) {
return -1;
}
word = ~words[u];
}
}
/*▲ 定位 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 运算 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Performs a logical <b>AND</b> of this target bit set with the
* argument bit set. This bit set is modified so that each bit in it
* has the value {@code true} if and only if it both initially
* had the value {@code true} and the corresponding bit in the
* bit set argument also had the value {@code true}.
*
* @param set a bit set
*/
// 对两个位集中的bit做"逻辑与"操作
public void and(BitSet set) {
if(this == set) {
return;
}
while(wordsInUse>set.wordsInUse) {
words[--wordsInUse] = 0;
}