Path: blob/master/src/java.base/share/classes/java/util/BitSet.java
41152 views
/*1* Copyright (c) 1995, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.util;2627import java.io.*;28import java.nio.ByteBuffer;29import java.nio.ByteOrder;30import java.nio.LongBuffer;31import java.util.function.IntConsumer;32import java.util.stream.IntStream;33import java.util.stream.StreamSupport;3435/**36* This class implements a vector of bits that grows as needed. Each37* component of the bit set has a {@code boolean} value. The38* bits of a {@code BitSet} are indexed by nonnegative integers.39* Individual indexed bits can be examined, set, or cleared. One40* {@code BitSet} may be used to modify the contents of another41* {@code BitSet} through logical AND, logical inclusive OR, and42* logical exclusive OR operations.43*44* <p>By default, all bits in the set initially have the value45* {@code false}.46*47* <p>Every bit set has a current size, which is the number of bits48* of space currently in use by the bit set. Note that the size is49* related to the implementation of a bit set, so it may change with50* implementation. The length of a bit set relates to logical length51* of a bit set and is defined independently of implementation.52*53* <p>Unless otherwise noted, passing a null parameter to any of the54* methods in a {@code BitSet} will result in a55* {@code NullPointerException}.56*57* <p>A {@code BitSet} is not safe for multithreaded use without58* external synchronization.59*60* @author Arthur van Hoff61* @author Michael McCloskey62* @author Martin Buchholz63* @since 1.064*/65public class BitSet implements Cloneable, java.io.Serializable {66/*67* BitSets are packed into arrays of "words." Currently a word is68* a long, which consists of 64 bits, requiring 6 address bits.69* The choice of word size is determined purely by performance concerns.70*/71private static final int ADDRESS_BITS_PER_WORD = 6;72private static final int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD;73private static final int BIT_INDEX_MASK = BITS_PER_WORD - 1;7475/* Used to shift left or right for a partial word mask */76private static final long WORD_MASK = 0xffffffffffffffffL;7778/**79* @serialField bits long[]80*81* The bits in this BitSet. The ith bit is stored in bits[i/64] at82* bit position i % 64 (where bit position 0 refers to the least83* significant bit and 63 refers to the most significant bit).84*/85@java.io.Serial86private static final ObjectStreamField[] serialPersistentFields = {87new ObjectStreamField("bits", long[].class),88};8990/**91* The internal field corresponding to the serialField "bits".92*/93private long[] words;9495/**96* The number of words in the logical size of this BitSet.97*/98private transient int wordsInUse = 0;99100/**101* Whether the size of "words" is user-specified. If so, we assume102* the user knows what he's doing and try harder to preserve it.103*/104private transient boolean sizeIsSticky = false;105106/* use serialVersionUID from JDK 1.0.2 for interoperability */107@java.io.Serial108private static final long serialVersionUID = 7997698588986878753L;109110/**111* Given a bit index, return word index containing it.112*/113private static int wordIndex(int bitIndex) {114return bitIndex >> ADDRESS_BITS_PER_WORD;115}116117/**118* Every public method must preserve these invariants.119*/120private void checkInvariants() {121assert(wordsInUse == 0 || words[wordsInUse - 1] != 0);122assert(wordsInUse >= 0 && wordsInUse <= words.length);123assert(wordsInUse == words.length || words[wordsInUse] == 0);124}125126/**127* Sets the field wordsInUse to the logical size in words of the bit set.128* WARNING:This method assumes that the number of words actually in use is129* less than or equal to the current value of wordsInUse!130*/131private void recalculateWordsInUse() {132// Traverse the bitset until a used word is found133int i;134for (i = wordsInUse-1; i >= 0; i--)135if (words[i] != 0)136break;137138wordsInUse = i+1; // The new logical size139}140141/**142* Creates a new bit set. All bits are initially {@code false}.143*/144public BitSet() {145initWords(BITS_PER_WORD);146sizeIsSticky = false;147}148149/**150* Creates a bit set whose initial size is large enough to explicitly151* represent bits with indices in the range {@code 0} through152* {@code nbits-1}. All bits are initially {@code false}.153*154* @param nbits the initial size of the bit set155* @throws NegativeArraySizeException if the specified initial size156* is negative157*/158public BitSet(int nbits) {159// nbits can't be negative; size 0 is OK160if (nbits < 0)161throw new NegativeArraySizeException("nbits < 0: " + nbits);162163initWords(nbits);164sizeIsSticky = true;165}166167private void initWords(int nbits) {168words = new long[wordIndex(nbits-1) + 1];169}170171/**172* Creates a bit set using words as the internal representation.173* The last word (if there is one) must be non-zero.174*/175private BitSet(long[] words) {176this.words = words;177this.wordsInUse = words.length;178checkInvariants();179}180181/**182* Returns a new bit set containing all the bits in the given long array.183*184* <p>More precisely,185* <br>{@code BitSet.valueOf(longs).get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}186* <br>for all {@code n < 64 * longs.length}.187*188* <p>This method is equivalent to189* {@code BitSet.valueOf(LongBuffer.wrap(longs))}.190*191* @param longs a long array containing a little-endian representation192* of a sequence of bits to be used as the initial bits of the193* new bit set194* @return a {@code BitSet} containing all the bits in the long array195* @since 1.7196*/197public static BitSet valueOf(long[] longs) {198int n;199for (n = longs.length; n > 0 && longs[n - 1] == 0; n--)200;201return new BitSet(Arrays.copyOf(longs, n));202}203204/**205* Returns a new bit set containing all the bits in the given long206* buffer between its position and limit.207*208* <p>More precisely,209* <br>{@code BitSet.valueOf(lb).get(n) == ((lb.get(lb.position()+n/64) & (1L<<(n%64))) != 0)}210* <br>for all {@code n < 64 * lb.remaining()}.211*212* <p>The long buffer is not modified by this method, and no213* reference to the buffer is retained by the bit set.214*215* @param lb a long buffer containing a little-endian representation216* of a sequence of bits between its position and limit, to be217* used as the initial bits of the new bit set218* @return a {@code BitSet} containing all the bits in the buffer in the219* specified range220* @since 1.7221*/222public static BitSet valueOf(LongBuffer lb) {223lb = lb.slice();224int n;225for (n = lb.remaining(); n > 0 && lb.get(n - 1) == 0; n--)226;227long[] words = new long[n];228lb.get(words);229return new BitSet(words);230}231232/**233* Returns a new bit set containing all the bits in the given byte array.234*235* <p>More precisely,236* <br>{@code BitSet.valueOf(bytes).get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}237* <br>for all {@code n < 8 * bytes.length}.238*239* <p>This method is equivalent to240* {@code BitSet.valueOf(ByteBuffer.wrap(bytes))}.241*242* @param bytes a byte array containing a little-endian243* representation of a sequence of bits to be used as the244* initial bits of the new bit set245* @return a {@code BitSet} containing all the bits in the byte array246* @since 1.7247*/248public static BitSet valueOf(byte[] bytes) {249return BitSet.valueOf(ByteBuffer.wrap(bytes));250}251252/**253* Returns a new bit set containing all the bits in the given byte254* buffer between its position and limit.255*256* <p>More precisely,257* <br>{@code BitSet.valueOf(bb).get(n) == ((bb.get(bb.position()+n/8) & (1<<(n%8))) != 0)}258* <br>for all {@code n < 8 * bb.remaining()}.259*260* <p>The byte buffer is not modified by this method, and no261* reference to the buffer is retained by the bit set.262*263* @param bb a byte buffer containing a little-endian representation264* of a sequence of bits between its position and limit, to be265* used as the initial bits of the new bit set266* @return a {@code BitSet} containing all the bits in the buffer in the267* specified range268* @since 1.7269*/270public static BitSet valueOf(ByteBuffer bb) {271bb = bb.slice().order(ByteOrder.LITTLE_ENDIAN);272int n;273for (n = bb.remaining(); n > 0 && bb.get(n - 1) == 0; n--)274;275long[] words = new long[(n + 7) / 8];276bb.limit(n);277int i = 0;278while (bb.remaining() >= 8)279words[i++] = bb.getLong();280for (int remaining = bb.remaining(), j = 0; j < remaining; j++)281words[i] |= (bb.get() & 0xffL) << (8 * j);282return new BitSet(words);283}284285/**286* Returns a new byte array containing all the bits in this bit set.287*288* <p>More precisely, if289* <br>{@code byte[] bytes = s.toByteArray();}290* <br>then {@code bytes.length == (s.length()+7)/8} and291* <br>{@code s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}292* <br>for all {@code n < 8 * bytes.length}.293*294* @return a byte array containing a little-endian representation295* of all the bits in this bit set296* @since 1.7297*/298public byte[] toByteArray() {299int n = wordsInUse;300if (n == 0)301return new byte[0];302int len = 8 * (n-1);303for (long x = words[n - 1]; x != 0; x >>>= 8)304len++;305byte[] bytes = new byte[len];306ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);307for (int i = 0; i < n - 1; i++)308bb.putLong(words[i]);309for (long x = words[n - 1]; x != 0; x >>>= 8)310bb.put((byte) (x & 0xff));311return bytes;312}313314/**315* Returns a new long array containing all the bits in this bit set.316*317* <p>More precisely, if318* <br>{@code long[] longs = s.toLongArray();}319* <br>then {@code longs.length == (s.length()+63)/64} and320* <br>{@code s.get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}321* <br>for all {@code n < 64 * longs.length}.322*323* @return a long array containing a little-endian representation324* of all the bits in this bit set325* @since 1.7326*/327public long[] toLongArray() {328return Arrays.copyOf(words, wordsInUse);329}330331/**332* Ensures that the BitSet can hold enough words.333* @param wordsRequired the minimum acceptable number of words.334*/335private void ensureCapacity(int wordsRequired) {336if (words.length < wordsRequired) {337// Allocate larger of doubled size or required size338int request = Math.max(2 * words.length, wordsRequired);339words = Arrays.copyOf(words, request);340sizeIsSticky = false;341}342}343344/**345* Ensures that the BitSet can accommodate a given wordIndex,346* temporarily violating the invariants. The caller must347* restore the invariants before returning to the user,348* possibly using recalculateWordsInUse().349* @param wordIndex the index to be accommodated.350*/351private void expandTo(int wordIndex) {352int wordsRequired = wordIndex+1;353if (wordsInUse < wordsRequired) {354ensureCapacity(wordsRequired);355wordsInUse = wordsRequired;356}357}358359/**360* Checks that fromIndex ... toIndex is a valid range of bit indices.361*/362private static void checkRange(int fromIndex, int toIndex) {363if (fromIndex < 0)364throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);365if (toIndex < 0)366throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex);367if (fromIndex > toIndex)368throw new IndexOutOfBoundsException("fromIndex: " + fromIndex +369" > toIndex: " + toIndex);370}371372/**373* Sets the bit at the specified index to the complement of its374* current value.375*376* @param bitIndex the index of the bit to flip377* @throws IndexOutOfBoundsException if the specified index is negative378* @since 1.4379*/380public void flip(int bitIndex) {381if (bitIndex < 0)382throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);383384int wordIndex = wordIndex(bitIndex);385expandTo(wordIndex);386387words[wordIndex] ^= (1L << bitIndex);388389recalculateWordsInUse();390checkInvariants();391}392393/**394* Sets each bit from the specified {@code fromIndex} (inclusive) to the395* specified {@code toIndex} (exclusive) to the complement of its current396* value.397*398* @param fromIndex index of the first bit to flip399* @param toIndex index after the last bit to flip400* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,401* or {@code toIndex} is negative, or {@code fromIndex} is402* larger than {@code toIndex}403* @since 1.4404*/405public void flip(int fromIndex, int toIndex) {406checkRange(fromIndex, toIndex);407408if (fromIndex == toIndex)409return;410411int startWordIndex = wordIndex(fromIndex);412int endWordIndex = wordIndex(toIndex - 1);413expandTo(endWordIndex);414415long firstWordMask = WORD_MASK << fromIndex;416long lastWordMask = WORD_MASK >>> -toIndex;417if (startWordIndex == endWordIndex) {418// Case 1: One word419words[startWordIndex] ^= (firstWordMask & lastWordMask);420} else {421// Case 2: Multiple words422// Handle first word423words[startWordIndex] ^= firstWordMask;424425// Handle intermediate words, if any426for (int i = startWordIndex+1; i < endWordIndex; i++)427words[i] ^= WORD_MASK;428429// Handle last word430words[endWordIndex] ^= lastWordMask;431}432433recalculateWordsInUse();434checkInvariants();435}436437/**438* Sets the bit at the specified index to {@code true}.439*440* @param bitIndex a bit index441* @throws IndexOutOfBoundsException if the specified index is negative442* @since 1.0443*/444public void set(int bitIndex) {445if (bitIndex < 0)446throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);447448int wordIndex = wordIndex(bitIndex);449expandTo(wordIndex);450451words[wordIndex] |= (1L << bitIndex); // Restores invariants452453checkInvariants();454}455456/**457* Sets the bit at the specified index to the specified value.458*459* @param bitIndex a bit index460* @param value a boolean value to set461* @throws IndexOutOfBoundsException if the specified index is negative462* @since 1.4463*/464public void set(int bitIndex, boolean value) {465if (value)466set(bitIndex);467else468clear(bitIndex);469}470471/**472* Sets the bits from the specified {@code fromIndex} (inclusive) to the473* specified {@code toIndex} (exclusive) to {@code true}.474*475* @param fromIndex index of the first bit to be set476* @param toIndex index after the last bit to be set477* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,478* or {@code toIndex} is negative, or {@code fromIndex} is479* larger than {@code toIndex}480* @since 1.4481*/482public void set(int fromIndex, int toIndex) {483checkRange(fromIndex, toIndex);484485if (fromIndex == toIndex)486return;487488// Increase capacity if necessary489int startWordIndex = wordIndex(fromIndex);490int endWordIndex = wordIndex(toIndex - 1);491expandTo(endWordIndex);492493long firstWordMask = WORD_MASK << fromIndex;494long lastWordMask = WORD_MASK >>> -toIndex;495if (startWordIndex == endWordIndex) {496// Case 1: One word497words[startWordIndex] |= (firstWordMask & lastWordMask);498} else {499// Case 2: Multiple words500// Handle first word501words[startWordIndex] |= firstWordMask;502503// Handle intermediate words, if any504for (int i = startWordIndex+1; i < endWordIndex; i++)505words[i] = WORD_MASK;506507// Handle last word (restores invariants)508words[endWordIndex] |= lastWordMask;509}510511checkInvariants();512}513514/**515* Sets the bits from the specified {@code fromIndex} (inclusive) to the516* specified {@code toIndex} (exclusive) to the specified value.517*518* @param fromIndex index of the first bit to be set519* @param toIndex index after the last bit to be set520* @param value value to set the selected bits to521* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,522* or {@code toIndex} is negative, or {@code fromIndex} is523* larger than {@code toIndex}524* @since 1.4525*/526public void set(int fromIndex, int toIndex, boolean value) {527if (value)528set(fromIndex, toIndex);529else530clear(fromIndex, toIndex);531}532533/**534* Sets the bit specified by the index to {@code false}.535*536* @param bitIndex the index of the bit to be cleared537* @throws IndexOutOfBoundsException if the specified index is negative538* @since 1.0539*/540public void clear(int bitIndex) {541if (bitIndex < 0)542throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);543544int wordIndex = wordIndex(bitIndex);545if (wordIndex >= wordsInUse)546return;547548words[wordIndex] &= ~(1L << bitIndex);549550recalculateWordsInUse();551checkInvariants();552}553554/**555* Sets the bits from the specified {@code fromIndex} (inclusive) to the556* specified {@code toIndex} (exclusive) to {@code false}.557*558* @param fromIndex index of the first bit to be cleared559* @param toIndex index after the last bit to be cleared560* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,561* or {@code toIndex} is negative, or {@code fromIndex} is562* larger than {@code toIndex}563* @since 1.4564*/565public void clear(int fromIndex, int toIndex) {566checkRange(fromIndex, toIndex);567568if (fromIndex == toIndex)569return;570571int startWordIndex = wordIndex(fromIndex);572if (startWordIndex >= wordsInUse)573return;574575int endWordIndex = wordIndex(toIndex - 1);576if (endWordIndex >= wordsInUse) {577toIndex = length();578endWordIndex = wordsInUse - 1;579}580581long firstWordMask = WORD_MASK << fromIndex;582long lastWordMask = WORD_MASK >>> -toIndex;583if (startWordIndex == endWordIndex) {584// Case 1: One word585words[startWordIndex] &= ~(firstWordMask & lastWordMask);586} else {587// Case 2: Multiple words588// Handle first word589words[startWordIndex] &= ~firstWordMask;590591// Handle intermediate words, if any592for (int i = startWordIndex+1; i < endWordIndex; i++)593words[i] = 0;594595// Handle last word596words[endWordIndex] &= ~lastWordMask;597}598599recalculateWordsInUse();600checkInvariants();601}602603/**604* Sets all of the bits in this BitSet to {@code false}.605*606* @since 1.4607*/608public void clear() {609while (wordsInUse > 0)610words[--wordsInUse] = 0;611}612613/**614* Returns the value of the bit with the specified index. The value615* is {@code true} if the bit with the index {@code bitIndex}616* is currently set in this {@code BitSet}; otherwise, the result617* is {@code false}.618*619* @param bitIndex the bit index620* @return the value of the bit with the specified index621* @throws IndexOutOfBoundsException if the specified index is negative622*/623public boolean get(int bitIndex) {624if (bitIndex < 0)625throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);626627checkInvariants();628629int wordIndex = wordIndex(bitIndex);630return (wordIndex < wordsInUse)631&& ((words[wordIndex] & (1L << bitIndex)) != 0);632}633634/**635* Returns a new {@code BitSet} composed of bits from this {@code BitSet}636* from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive).637*638* @param fromIndex index of the first bit to include639* @param toIndex index after the last bit to include640* @return a new {@code BitSet} from a range of this {@code BitSet}641* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,642* or {@code toIndex} is negative, or {@code fromIndex} is643* larger than {@code toIndex}644* @since 1.4645*/646public BitSet get(int fromIndex, int toIndex) {647checkRange(fromIndex, toIndex);648649checkInvariants();650651int len = length();652653// If no set bits in range return empty bitset654if (len <= fromIndex || fromIndex == toIndex)655return new BitSet(0);656657// An optimization658if (toIndex > len)659toIndex = len;660661BitSet result = new BitSet(toIndex - fromIndex);662int targetWords = wordIndex(toIndex - fromIndex - 1) + 1;663int sourceIndex = wordIndex(fromIndex);664boolean wordAligned = ((fromIndex & BIT_INDEX_MASK) == 0);665666// Process all words but the last word667for (int i = 0; i < targetWords - 1; i++, sourceIndex++)668result.words[i] = wordAligned ? words[sourceIndex] :669(words[sourceIndex] >>> fromIndex) |670(words[sourceIndex+1] << -fromIndex);671672// Process the last word673long lastWordMask = WORD_MASK >>> -toIndex;674result.words[targetWords - 1] =675((toIndex-1) & BIT_INDEX_MASK) < (fromIndex & BIT_INDEX_MASK)676? /* straddles source words */677((words[sourceIndex] >>> fromIndex) |678(words[sourceIndex+1] & lastWordMask) << -fromIndex)679:680((words[sourceIndex] & lastWordMask) >>> fromIndex);681682// Set wordsInUse correctly683result.wordsInUse = targetWords;684result.recalculateWordsInUse();685result.checkInvariants();686687return result;688}689690/**691* Returns the index of the first bit that is set to {@code true}692* that occurs on or after the specified starting index. If no such693* bit exists then {@code -1} is returned.694*695* <p>To iterate over the {@code true} bits in a {@code BitSet},696* use the following loop:697*698* <pre> {@code699* for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {700* // operate on index i here701* if (i == Integer.MAX_VALUE) {702* break; // or (i+1) would overflow703* }704* }}</pre>705*706* @param fromIndex the index to start checking from (inclusive)707* @return the index of the next set bit, or {@code -1} if there708* is no such bit709* @throws IndexOutOfBoundsException if the specified index is negative710* @since 1.4711*/712public int nextSetBit(int fromIndex) {713if (fromIndex < 0)714throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);715716checkInvariants();717718int u = wordIndex(fromIndex);719if (u >= wordsInUse)720return -1;721722long word = words[u] & (WORD_MASK << fromIndex);723724while (true) {725if (word != 0)726return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);727if (++u == wordsInUse)728return -1;729word = words[u];730}731}732733/**734* Returns the index of the first bit that is set to {@code false}735* that occurs on or after the specified starting index.736*737* @param fromIndex the index to start checking from (inclusive)738* @return the index of the next clear bit739* @throws IndexOutOfBoundsException if the specified index is negative740* @since 1.4741*/742public int nextClearBit(int fromIndex) {743// Neither spec nor implementation handle bitsets of maximal length.744// See 4816253.745if (fromIndex < 0)746throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);747748checkInvariants();749750int u = wordIndex(fromIndex);751if (u >= wordsInUse)752return fromIndex;753754long word = ~words[u] & (WORD_MASK << fromIndex);755756while (true) {757if (word != 0)758return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);759if (++u == wordsInUse)760return wordsInUse * BITS_PER_WORD;761word = ~words[u];762}763}764765/**766* Returns the index of the nearest bit that is set to {@code true}767* that occurs on or before the specified starting index.768* If no such bit exists, or if {@code -1} is given as the769* starting index, then {@code -1} is returned.770*771* <p>To iterate over the {@code true} bits in a {@code BitSet},772* use the following loop:773*774* <pre> {@code775* for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {776* // operate on index i here777* }}</pre>778*779* @param fromIndex the index to start checking from (inclusive)780* @return the index of the previous set bit, or {@code -1} if there781* is no such bit782* @throws IndexOutOfBoundsException if the specified index is less783* than {@code -1}784* @since 1.7785*/786public int previousSetBit(int fromIndex) {787if (fromIndex < 0) {788if (fromIndex == -1)789return -1;790throw new IndexOutOfBoundsException(791"fromIndex < -1: " + fromIndex);792}793794checkInvariants();795796int u = wordIndex(fromIndex);797if (u >= wordsInUse)798return length() - 1;799800long word = words[u] & (WORD_MASK >>> -(fromIndex+1));801802while (true) {803if (word != 0)804return (u+1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word);805if (u-- == 0)806return -1;807word = words[u];808}809}810811/**812* Returns the index of the nearest bit that is set to {@code false}813* that occurs on or before the specified starting index.814* If no such bit exists, or if {@code -1} is given as the815* starting index, then {@code -1} is returned.816*817* @param fromIndex the index to start checking from (inclusive)818* @return the index of the previous clear bit, or {@code -1} if there819* is no such bit820* @throws IndexOutOfBoundsException if the specified index is less821* than {@code -1}822* @since 1.7823*/824public int previousClearBit(int fromIndex) {825if (fromIndex < 0) {826if (fromIndex == -1)827return -1;828throw new IndexOutOfBoundsException(829"fromIndex < -1: " + fromIndex);830}831832checkInvariants();833834int u = wordIndex(fromIndex);835if (u >= wordsInUse)836return fromIndex;837838long word = ~words[u] & (WORD_MASK >>> -(fromIndex+1));839840while (true) {841if (word != 0)842return (u+1) * BITS_PER_WORD -1 - Long.numberOfLeadingZeros(word);843if (u-- == 0)844return -1;845word = ~words[u];846}847}848849/**850* Returns the "logical size" of this {@code BitSet}: the index of851* the highest set bit in the {@code BitSet} plus one. Returns zero852* if the {@code BitSet} contains no set bits.853*854* @return the logical size of this {@code BitSet}855* @since 1.2856*/857public int length() {858if (wordsInUse == 0)859return 0;860861return BITS_PER_WORD * (wordsInUse - 1) +862(BITS_PER_WORD - Long.numberOfLeadingZeros(words[wordsInUse - 1]));863}864865/**866* Returns true if this {@code BitSet} contains no bits that are set867* to {@code true}.868*869* @return boolean indicating whether this {@code BitSet} is empty870* @since 1.4871*/872public boolean isEmpty() {873return wordsInUse == 0;874}875876/**877* Returns true if the specified {@code BitSet} has any bits set to878* {@code true} that are also set to {@code true} in this {@code BitSet}.879*880* @param set {@code BitSet} to intersect with881* @return boolean indicating whether this {@code BitSet} intersects882* the specified {@code BitSet}883* @since 1.4884*/885public boolean intersects(BitSet set) {886for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)887if ((words[i] & set.words[i]) != 0)888return true;889return false;890}891892/**893* Returns the number of bits set to {@code true} in this {@code BitSet}.894*895* @return the number of bits set to {@code true} in this {@code BitSet}896* @since 1.4897*/898public int cardinality() {899int sum = 0;900for (int i = 0; i < wordsInUse; i++)901sum += Long.bitCount(words[i]);902return sum;903}904905/**906* Performs a logical <b>AND</b> of this target bit set with the907* argument bit set. This bit set is modified so that each bit in it908* has the value {@code true} if and only if it both initially909* had the value {@code true} and the corresponding bit in the910* bit set argument also had the value {@code true}.911*912* @param set a bit set913*/914public void and(BitSet set) {915if (this == set)916return;917918while (wordsInUse > set.wordsInUse)919words[--wordsInUse] = 0;920921// Perform logical AND on words in common922for (int i = 0; i < wordsInUse; i++)923words[i] &= set.words[i];924925recalculateWordsInUse();926checkInvariants();927}928929/**930* Performs a logical <b>OR</b> of this bit set with the bit set931* argument. This bit set is modified so that a bit in it has the932* value {@code true} if and only if it either already had the933* value {@code true} or the corresponding bit in the bit set934* argument has the value {@code true}.935*936* @param set a bit set937*/938public void or(BitSet set) {939if (this == set)940return;941942int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);943944if (wordsInUse < set.wordsInUse) {945ensureCapacity(set.wordsInUse);946wordsInUse = set.wordsInUse;947}948949// Perform logical OR on words in common950for (int i = 0; i < wordsInCommon; i++)951words[i] |= set.words[i];952953// Copy any remaining words954if (wordsInCommon < set.wordsInUse)955System.arraycopy(set.words, wordsInCommon,956words, wordsInCommon,957wordsInUse - wordsInCommon);958959// recalculateWordsInUse() is unnecessary960checkInvariants();961}962963/**964* Performs a logical <b>XOR</b> of this bit set with the bit set965* argument. This bit set is modified so that a bit in it has the966* value {@code true} if and only if one of the following967* statements holds:968* <ul>969* <li>The bit initially has the value {@code true}, and the970* corresponding bit in the argument has the value {@code false}.971* <li>The bit initially has the value {@code false}, and the972* corresponding bit in the argument has the value {@code true}.973* </ul>974*975* @param set a bit set976*/977public void xor(BitSet set) {978int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);979980if (wordsInUse < set.wordsInUse) {981ensureCapacity(set.wordsInUse);982wordsInUse = set.wordsInUse;983}984985// Perform logical XOR on words in common986for (int i = 0; i < wordsInCommon; i++)987words[i] ^= set.words[i];988989// Copy any remaining words990if (wordsInCommon < set.wordsInUse)991System.arraycopy(set.words, wordsInCommon,992words, wordsInCommon,993set.wordsInUse - wordsInCommon);994995recalculateWordsInUse();996checkInvariants();997}998999/**1000* Clears all of the bits in this {@code BitSet} whose corresponding1001* bit is set in the specified {@code BitSet}.1002*1003* @param set the {@code BitSet} with which to mask this1004* {@code BitSet}1005* @since 1.21006*/1007public void andNot(BitSet set) {1008// Perform logical (a & !b) on words in common1009for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)1010words[i] &= ~set.words[i];10111012recalculateWordsInUse();1013checkInvariants();1014}10151016/**1017* Returns the hash code value for this bit set. The hash code depends1018* only on which bits are set within this {@code BitSet}.1019*1020* <p>The hash code is defined to be the result of the following1021* calculation:1022* <pre> {@code1023* public int hashCode() {1024* long h = 1234;1025* long[] words = toLongArray();1026* for (int i = words.length; --i >= 0; )1027* h ^= words[i] * (i + 1);1028* return (int)((h >> 32) ^ h);1029* }}</pre>1030* Note that the hash code changes if the set of bits is altered.1031*1032* @return the hash code value for this bit set1033*/1034public int hashCode() {1035long h = 1234;1036for (int i = wordsInUse; --i >= 0; )1037h ^= words[i] * (i + 1);10381039return (int)((h >> 32) ^ h);1040}10411042/**1043* Returns the number of bits of space actually in use by this1044* {@code BitSet} to represent bit values.1045* The maximum element in the set is the size - 1st element.1046*1047* @return the number of bits currently in this bit set1048*/1049public int size() {1050return words.length * BITS_PER_WORD;1051}10521053/**1054* Compares this object against the specified object.1055* The result is {@code true} if and only if the argument is1056* not {@code null} and is a {@code BitSet} object that has1057* exactly the same set of bits set to {@code true} as this bit1058* set. That is, for every nonnegative {@code int} index {@code k},1059* <pre>((BitSet)obj).get(k) == this.get(k)</pre>1060* must be true. The current sizes of the two bit sets are not compared.1061*1062* @param obj the object to compare with1063* @return {@code true} if the objects are the same;1064* {@code false} otherwise1065* @see #size()1066*/1067public boolean equals(Object obj) {1068if (!(obj instanceof BitSet set))1069return false;1070if (this == obj)1071return true;10721073checkInvariants();1074set.checkInvariants();10751076if (wordsInUse != set.wordsInUse)1077return false;10781079// Check words in use by both BitSets1080for (int i = 0; i < wordsInUse; i++)1081if (words[i] != set.words[i])1082return false;10831084return true;1085}10861087/**1088* Cloning this {@code BitSet} produces a new {@code BitSet}1089* that is equal to it.1090* The clone of the bit set is another bit set that has exactly the1091* same bits set to {@code true} as this bit set.1092*1093* @return a clone of this bit set1094* @see #size()1095*/1096public Object clone() {1097if (! sizeIsSticky)1098trimToSize();10991100try {1101BitSet result = (BitSet) super.clone();1102result.words = words.clone();1103result.checkInvariants();1104return result;1105} catch (CloneNotSupportedException e) {1106throw new InternalError(e);1107}1108}11091110/**1111* Attempts to reduce internal storage used for the bits in this bit set.1112* Calling this method may, but is not required to, affect the value1113* returned by a subsequent call to the {@link #size()} method.1114*/1115private void trimToSize() {1116if (wordsInUse != words.length) {1117words = Arrays.copyOf(words, wordsInUse);1118checkInvariants();1119}1120}11211122/**1123* Save the state of the {@code BitSet} instance to a stream (i.e.,1124* serialize it).1125*/1126@java.io.Serial1127private void writeObject(ObjectOutputStream s)1128throws IOException {11291130checkInvariants();11311132if (! sizeIsSticky)1133trimToSize();11341135ObjectOutputStream.PutField fields = s.putFields();1136fields.put("bits", words);1137s.writeFields();1138}11391140/**1141* Reconstitute the {@code BitSet} instance from a stream (i.e.,1142* deserialize it).1143*/1144@java.io.Serial1145private void readObject(ObjectInputStream s)1146throws IOException, ClassNotFoundException {11471148ObjectInputStream.GetField fields = s.readFields();1149words = (long[]) fields.get("bits", null);11501151// Assume maximum length then find real length1152// because recalculateWordsInUse assumes maintenance1153// or reduction in logical size1154wordsInUse = words.length;1155recalculateWordsInUse();1156sizeIsSticky = (words.length > 0 && words[words.length-1] == 0L); // heuristic1157checkInvariants();1158}11591160/**1161* Returns a string representation of this bit set. For every index1162* for which this {@code BitSet} contains a bit in the set1163* state, the decimal representation of that index is included in1164* the result. Such indices are listed in order from lowest to1165* highest, separated by ", " (a comma and a space) and1166* surrounded by braces, resulting in the usual mathematical1167* notation for a set of integers.1168*1169* <p>Example:1170* <pre>1171* BitSet drPepper = new BitSet();</pre>1172* Now {@code drPepper.toString()} returns "{@code {}}".1173* <pre>1174* drPepper.set(2);</pre>1175* Now {@code drPepper.toString()} returns "{@code {2}}".1176* <pre>1177* drPepper.set(4);1178* drPepper.set(10);</pre>1179* Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}".1180*1181* @return a string representation of this bit set1182*/1183public String toString() {1184checkInvariants();11851186final int MAX_INITIAL_CAPACITY = Integer.MAX_VALUE - 8;1187int numBits = (wordsInUse > 128) ?1188cardinality() : wordsInUse * BITS_PER_WORD;1189// Avoid overflow in the case of a humongous numBits1190int initialCapacity = (numBits <= (MAX_INITIAL_CAPACITY - 2) / 6) ?11916 * numBits + 2 : MAX_INITIAL_CAPACITY;1192StringBuilder b = new StringBuilder(initialCapacity);1193b.append('{');11941195int i = nextSetBit(0);1196if (i != -1) {1197b.append(i);1198while (true) {1199if (++i < 0) break;1200if ((i = nextSetBit(i)) < 0) break;1201int endOfRun = nextClearBit(i);1202do { b.append(", ").append(i); }1203while (++i != endOfRun);1204}1205}12061207b.append('}');1208return b.toString();1209}12101211/**1212* Returns a stream of indices for which this {@code BitSet}1213* contains a bit in the set state. The indices are returned1214* in order, from lowest to highest. The size of the stream1215* is the number of bits in the set state, equal to the value1216* returned by the {@link #cardinality()} method.1217*1218* <p>The stream binds to this bit set when the terminal stream operation1219* commences (specifically, the spliterator for the stream is1220* <a href="Spliterator.html#binding"><em>late-binding</em></a>). If the1221* bit set is modified during that operation then the result is undefined.1222*1223* @return a stream of integers representing set indices1224* @since 1.81225*/1226public IntStream stream() {1227class BitSetSpliterator implements Spliterator.OfInt {1228private int index; // current bit index for a set bit1229private int fence; // -1 until used; then one past last bit index1230private int est; // size estimate1231private boolean root; // true if root and not split1232// root == true then size estimate is accurate1233// index == -1 or index >= fence if fully traversed1234// Special case when the max bit set is Integer.MAX_VALUE12351236BitSetSpliterator(int origin, int fence, int est, boolean root) {1237this.index = origin;1238this.fence = fence;1239this.est = est;1240this.root = root;1241}12421243private int getFence() {1244int hi;1245if ((hi = fence) < 0) {1246// Round up fence to maximum cardinality for allocated words1247// This is sufficient and cheap for sequential access1248// When splitting this value is lowered1249hi = fence = (wordsInUse >= wordIndex(Integer.MAX_VALUE))1250? Integer.MAX_VALUE1251: wordsInUse << ADDRESS_BITS_PER_WORD;1252est = cardinality();1253index = nextSetBit(0);1254}1255return hi;1256}12571258@Override1259public boolean tryAdvance(IntConsumer action) {1260Objects.requireNonNull(action);12611262int hi = getFence();1263int i = index;1264if (i < 0 || i >= hi) {1265// Check if there is a final bit set for Integer.MAX_VALUE1266if (i == Integer.MAX_VALUE && hi == Integer.MAX_VALUE) {1267index = -1;1268action.accept(Integer.MAX_VALUE);1269return true;1270}1271return false;1272}12731274index = nextSetBit(i + 1, wordIndex(hi - 1));1275action.accept(i);1276return true;1277}12781279@Override1280public void forEachRemaining(IntConsumer action) {1281Objects.requireNonNull(action);12821283int hi = getFence();1284int i = index;1285index = -1;12861287if (i >= 0 && i < hi) {1288action.accept(i++);12891290int u = wordIndex(i); // next lower word bound1291int v = wordIndex(hi - 1); // upper word bound12921293words_loop:1294for (; u <= v && i <= hi; u++, i = u << ADDRESS_BITS_PER_WORD) {1295long word = words[u] & (WORD_MASK << i);1296while (word != 0) {1297i = (u << ADDRESS_BITS_PER_WORD) + Long.numberOfTrailingZeros(word);1298if (i >= hi) {1299// Break out of outer loop to ensure check of1300// Integer.MAX_VALUE bit set1301break words_loop;1302}13031304// Flip the set bit1305word &= ~(1L << i);13061307action.accept(i);1308}1309}1310}13111312// Check if there is a final bit set for Integer.MAX_VALUE1313if (i == Integer.MAX_VALUE && hi == Integer.MAX_VALUE) {1314action.accept(Integer.MAX_VALUE);1315}1316}13171318@Override1319public OfInt trySplit() {1320int hi = getFence();1321int lo = index;1322if (lo < 0) {1323return null;1324}13251326// Lower the fence to be the upper bound of last bit set1327// The index is the first bit set, thus this spliterator1328// covers one bit and cannot be split, or two or more1329// bits1330hi = fence = (hi < Integer.MAX_VALUE || !get(Integer.MAX_VALUE))1331? previousSetBit(hi - 1) + 11332: Integer.MAX_VALUE;13331334// Find the mid point1335int mid = (lo + hi) >>> 1;1336if (lo >= mid) {1337return null;1338}13391340// Raise the index of this spliterator to be the next set bit1341// from the mid point1342index = nextSetBit(mid, wordIndex(hi - 1));1343root = false;13441345// Don't lower the fence (mid point) of the returned spliterator,1346// traversal or further splitting will do that work1347return new BitSetSpliterator(lo, mid, est >>>= 1, false);1348}13491350@Override1351public long estimateSize() {1352getFence(); // force init1353return est;1354}13551356@Override1357public int characteristics() {1358// Only sized when root and not split1359return (root ? Spliterator.SIZED : 0) |1360Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED;1361}13621363@Override1364public Comparator<? super Integer> getComparator() {1365return null;1366}1367}1368return StreamSupport.intStream(new BitSetSpliterator(0, -1, 0, true), false);1369}13701371/**1372* Returns the index of the first bit that is set to {@code true}1373* that occurs on or after the specified starting index and up to and1374* including the specified word index1375* If no such bit exists then {@code -1} is returned.1376*1377* @param fromIndex the index to start checking from (inclusive)1378* @param toWordIndex the last word index to check (inclusive)1379* @return the index of the next set bit, or {@code -1} if there1380* is no such bit1381*/1382private int nextSetBit(int fromIndex, int toWordIndex) {1383int u = wordIndex(fromIndex);1384// Check if out of bounds1385if (u > toWordIndex)1386return -1;13871388long word = words[u] & (WORD_MASK << fromIndex);13891390while (true) {1391if (word != 0)1392return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);1393// Check if out of bounds1394if (++u > toWordIndex)1395return -1;1396word = words[u];1397}1398}13991400}140114021403