Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/util/BitSet.java
38829 views
/*1* Copyright (c) 1995, 2014, 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.stream.IntStream;32import java.util.stream.StreamSupport;3334/**35* This class implements a vector of bits that grows as needed. Each36* component of the bit set has a {@code boolean} value. The37* bits of a {@code BitSet} are indexed by nonnegative integers.38* Individual indexed bits can be examined, set, or cleared. One39* {@code BitSet} may be used to modify the contents of another40* {@code BitSet} through logical AND, logical inclusive OR, and41* logical exclusive OR operations.42*43* <p>By default, all bits in the set initially have the value44* {@code false}.45*46* <p>Every bit set has a current size, which is the number of bits47* of space currently in use by the bit set. Note that the size is48* related to the implementation of a bit set, so it may change with49* implementation. The length of a bit set relates to logical length50* of a bit set and is defined independently of implementation.51*52* <p>Unless otherwise noted, passing a null parameter to any of the53* methods in a {@code BitSet} will result in a54* {@code NullPointerException}.55*56* <p>A {@code BitSet} is not safe for multithreaded use without57* external synchronization.58*59* @author Arthur van Hoff60* @author Michael McCloskey61* @author Martin Buchholz62* @since JDK1.063*/64public class BitSet implements Cloneable, java.io.Serializable {65/*66* BitSets are packed into arrays of "words." Currently a word is67* a long, which consists of 64 bits, requiring 6 address bits.68* The choice of word size is determined purely by performance concerns.69*/70private final static int ADDRESS_BITS_PER_WORD = 6;71private final static int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD;72private final static int BIT_INDEX_MASK = BITS_PER_WORD - 1;7374/* Used to shift left or right for a partial word mask */75private static final long WORD_MASK = 0xffffffffffffffffL;7677/**78* @serialField bits long[]79*80* The bits in this BitSet. The ith bit is stored in bits[i/64] at81* bit position i % 64 (where bit position 0 refers to the least82* significant bit and 63 refers to the most significant bit).83*/84private static final ObjectStreamField[] serialPersistentFields = {85new ObjectStreamField("bits", long[].class),86};8788/**89* The internal field corresponding to the serialField "bits".90*/91private long[] words;9293/**94* The number of words in the logical size of this BitSet.95*/96private transient int wordsInUse = 0;9798/**99* Whether the size of "words" is user-specified. If so, we assume100* the user knows what he's doing and try harder to preserve it.101*/102private transient boolean sizeIsSticky = false;103104/* use serialVersionUID from JDK 1.0.2 for interoperability */105private static final long serialVersionUID = 7997698588986878753L;106107/**108* Given a bit index, return word index containing it.109*/110private static int wordIndex(int bitIndex) {111return bitIndex >> ADDRESS_BITS_PER_WORD;112}113114/**115* Every public method must preserve these invariants.116*/117private void checkInvariants() {118assert(wordsInUse == 0 || words[wordsInUse - 1] != 0);119assert(wordsInUse >= 0 && wordsInUse <= words.length);120assert(wordsInUse == words.length || words[wordsInUse] == 0);121}122123/**124* Sets the field wordsInUse to the logical size in words of the bit set.125* WARNING:This method assumes that the number of words actually in use is126* less than or equal to the current value of wordsInUse!127*/128private void recalculateWordsInUse() {129// Traverse the bitset until a used word is found130int i;131for (i = wordsInUse-1; i >= 0; i--)132if (words[i] != 0)133break;134135wordsInUse = i+1; // The new logical size136}137138/**139* Creates a new bit set. All bits are initially {@code false}.140*/141public BitSet() {142initWords(BITS_PER_WORD);143sizeIsSticky = false;144}145146/**147* Creates a bit set whose initial size is large enough to explicitly148* represent bits with indices in the range {@code 0} through149* {@code nbits-1}. All bits are initially {@code false}.150*151* @param nbits the initial size of the bit set152* @throws NegativeArraySizeException if the specified initial size153* is negative154*/155public BitSet(int nbits) {156// nbits can't be negative; size 0 is OK157if (nbits < 0)158throw new NegativeArraySizeException("nbits < 0: " + nbits);159160initWords(nbits);161sizeIsSticky = true;162}163164private void initWords(int nbits) {165words = new long[wordIndex(nbits-1) + 1];166}167168/**169* Creates a bit set using words as the internal representation.170* The last word (if there is one) must be non-zero.171*/172private BitSet(long[] words) {173this.words = words;174this.wordsInUse = words.length;175checkInvariants();176}177178/**179* Returns a new bit set containing all the bits in the given long array.180*181* <p>More precisely,182* <br>{@code BitSet.valueOf(longs).get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}183* <br>for all {@code n < 64 * longs.length}.184*185* <p>This method is equivalent to186* {@code BitSet.valueOf(LongBuffer.wrap(longs))}.187*188* @param longs a long array containing a little-endian representation189* of a sequence of bits to be used as the initial bits of the190* new bit set191* @return a {@code BitSet} containing all the bits in the long array192* @since 1.7193*/194public static BitSet valueOf(long[] longs) {195int n;196for (n = longs.length; n > 0 && longs[n - 1] == 0; n--)197;198return new BitSet(Arrays.copyOf(longs, n));199}200201/**202* Returns a new bit set containing all the bits in the given long203* buffer between its position and limit.204*205* <p>More precisely,206* <br>{@code BitSet.valueOf(lb).get(n) == ((lb.get(lb.position()+n/64) & (1L<<(n%64))) != 0)}207* <br>for all {@code n < 64 * lb.remaining()}.208*209* <p>The long buffer is not modified by this method, and no210* reference to the buffer is retained by the bit set.211*212* @param lb a long buffer containing a little-endian representation213* of a sequence of bits between its position and limit, to be214* used as the initial bits of the new bit set215* @return a {@code BitSet} containing all the bits in the buffer in the216* specified range217* @since 1.7218*/219public static BitSet valueOf(LongBuffer lb) {220lb = lb.slice();221int n;222for (n = lb.remaining(); n > 0 && lb.get(n - 1) == 0; n--)223;224long[] words = new long[n];225lb.get(words);226return new BitSet(words);227}228229/**230* Returns a new bit set containing all the bits in the given byte array.231*232* <p>More precisely,233* <br>{@code BitSet.valueOf(bytes).get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}234* <br>for all {@code n < 8 * bytes.length}.235*236* <p>This method is equivalent to237* {@code BitSet.valueOf(ByteBuffer.wrap(bytes))}.238*239* @param bytes a byte array containing a little-endian240* representation of a sequence of bits to be used as the241* initial bits of the new bit set242* @return a {@code BitSet} containing all the bits in the byte array243* @since 1.7244*/245public static BitSet valueOf(byte[] bytes) {246return BitSet.valueOf(ByteBuffer.wrap(bytes));247}248249/**250* Returns a new bit set containing all the bits in the given byte251* buffer between its position and limit.252*253* <p>More precisely,254* <br>{@code BitSet.valueOf(bb).get(n) == ((bb.get(bb.position()+n/8) & (1<<(n%8))) != 0)}255* <br>for all {@code n < 8 * bb.remaining()}.256*257* <p>The byte buffer is not modified by this method, and no258* reference to the buffer is retained by the bit set.259*260* @param bb a byte buffer containing a little-endian representation261* of a sequence of bits between its position and limit, to be262* used as the initial bits of the new bit set263* @return a {@code BitSet} containing all the bits in the buffer in the264* specified range265* @since 1.7266*/267public static BitSet valueOf(ByteBuffer bb) {268bb = bb.slice().order(ByteOrder.LITTLE_ENDIAN);269int n;270for (n = bb.remaining(); n > 0 && bb.get(n - 1) == 0; n--)271;272long[] words = new long[(n + 7) / 8];273bb.limit(n);274int i = 0;275while (bb.remaining() >= 8)276words[i++] = bb.getLong();277for (int remaining = bb.remaining(), j = 0; j < remaining; j++)278words[i] |= (bb.get() & 0xffL) << (8 * j);279return new BitSet(words);280}281282/**283* Returns a new byte array containing all the bits in this bit set.284*285* <p>More precisely, if286* <br>{@code byte[] bytes = s.toByteArray();}287* <br>then {@code bytes.length == (s.length()+7)/8} and288* <br>{@code s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}289* <br>for all {@code n < 8 * bytes.length}.290*291* @return a byte array containing a little-endian representation292* of all the bits in this bit set293* @since 1.7294*/295public byte[] toByteArray() {296int n = wordsInUse;297if (n == 0)298return new byte[0];299int len = 8 * (n-1);300for (long x = words[n - 1]; x != 0; x >>>= 8)301len++;302byte[] bytes = new byte[len];303ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);304for (int i = 0; i < n - 1; i++)305bb.putLong(words[i]);306for (long x = words[n - 1]; x != 0; x >>>= 8)307bb.put((byte) (x & 0xff));308return bytes;309}310311/**312* Returns a new long array containing all the bits in this bit set.313*314* <p>More precisely, if315* <br>{@code long[] longs = s.toLongArray();}316* <br>then {@code longs.length == (s.length()+63)/64} and317* <br>{@code s.get(n) == ((longs[n/64] & (1L<<(n%64))) != 0)}318* <br>for all {@code n < 64 * longs.length}.319*320* @return a long array containing a little-endian representation321* of all the bits in this bit set322* @since 1.7323*/324public long[] toLongArray() {325return Arrays.copyOf(words, wordsInUse);326}327328/**329* Ensures that the BitSet can hold enough words.330* @param wordsRequired the minimum acceptable number of words.331*/332private void ensureCapacity(int wordsRequired) {333if (words.length < wordsRequired) {334// Allocate larger of doubled size or required size335int request = Math.max(2 * words.length, wordsRequired);336words = Arrays.copyOf(words, request);337sizeIsSticky = false;338}339}340341/**342* Ensures that the BitSet can accommodate a given wordIndex,343* temporarily violating the invariants. The caller must344* restore the invariants before returning to the user,345* possibly using recalculateWordsInUse().346* @param wordIndex the index to be accommodated.347*/348private void expandTo(int wordIndex) {349int wordsRequired = wordIndex+1;350if (wordsInUse < wordsRequired) {351ensureCapacity(wordsRequired);352wordsInUse = wordsRequired;353}354}355356/**357* Checks that fromIndex ... toIndex is a valid range of bit indices.358*/359private static void checkRange(int fromIndex, int toIndex) {360if (fromIndex < 0)361throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);362if (toIndex < 0)363throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex);364if (fromIndex > toIndex)365throw new IndexOutOfBoundsException("fromIndex: " + fromIndex +366" > toIndex: " + toIndex);367}368369/**370* Sets the bit at the specified index to the complement of its371* current value.372*373* @param bitIndex the index of the bit to flip374* @throws IndexOutOfBoundsException if the specified index is negative375* @since 1.4376*/377public void flip(int bitIndex) {378if (bitIndex < 0)379throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);380381int wordIndex = wordIndex(bitIndex);382expandTo(wordIndex);383384words[wordIndex] ^= (1L << bitIndex);385386recalculateWordsInUse();387checkInvariants();388}389390/**391* Sets each bit from the specified {@code fromIndex} (inclusive) to the392* specified {@code toIndex} (exclusive) to the complement of its current393* value.394*395* @param fromIndex index of the first bit to flip396* @param toIndex index after the last bit to flip397* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,398* or {@code toIndex} is negative, or {@code fromIndex} is399* larger than {@code toIndex}400* @since 1.4401*/402public void flip(int fromIndex, int toIndex) {403checkRange(fromIndex, toIndex);404405if (fromIndex == toIndex)406return;407408int startWordIndex = wordIndex(fromIndex);409int endWordIndex = wordIndex(toIndex - 1);410expandTo(endWordIndex);411412long firstWordMask = WORD_MASK << fromIndex;413long lastWordMask = WORD_MASK >>> -toIndex;414if (startWordIndex == endWordIndex) {415// Case 1: One word416words[startWordIndex] ^= (firstWordMask & lastWordMask);417} else {418// Case 2: Multiple words419// Handle first word420words[startWordIndex] ^= firstWordMask;421422// Handle intermediate words, if any423for (int i = startWordIndex+1; i < endWordIndex; i++)424words[i] ^= WORD_MASK;425426// Handle last word427words[endWordIndex] ^= lastWordMask;428}429430recalculateWordsInUse();431checkInvariants();432}433434/**435* Sets the bit at the specified index to {@code true}.436*437* @param bitIndex a bit index438* @throws IndexOutOfBoundsException if the specified index is negative439* @since JDK1.0440*/441public void set(int bitIndex) {442if (bitIndex < 0)443throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);444445int wordIndex = wordIndex(bitIndex);446expandTo(wordIndex);447448words[wordIndex] |= (1L << bitIndex); // Restores invariants449450checkInvariants();451}452453/**454* Sets the bit at the specified index to the specified value.455*456* @param bitIndex a bit index457* @param value a boolean value to set458* @throws IndexOutOfBoundsException if the specified index is negative459* @since 1.4460*/461public void set(int bitIndex, boolean value) {462if (value)463set(bitIndex);464else465clear(bitIndex);466}467468/**469* Sets the bits from the specified {@code fromIndex} (inclusive) to the470* specified {@code toIndex} (exclusive) to {@code true}.471*472* @param fromIndex index of the first bit to be set473* @param toIndex index after the last bit to be set474* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,475* or {@code toIndex} is negative, or {@code fromIndex} is476* larger than {@code toIndex}477* @since 1.4478*/479public void set(int fromIndex, int toIndex) {480checkRange(fromIndex, toIndex);481482if (fromIndex == toIndex)483return;484485// Increase capacity if necessary486int startWordIndex = wordIndex(fromIndex);487int endWordIndex = wordIndex(toIndex - 1);488expandTo(endWordIndex);489490long firstWordMask = WORD_MASK << fromIndex;491long lastWordMask = WORD_MASK >>> -toIndex;492if (startWordIndex == endWordIndex) {493// Case 1: One word494words[startWordIndex] |= (firstWordMask & lastWordMask);495} else {496// Case 2: Multiple words497// Handle first word498words[startWordIndex] |= firstWordMask;499500// Handle intermediate words, if any501for (int i = startWordIndex+1; i < endWordIndex; i++)502words[i] = WORD_MASK;503504// Handle last word (restores invariants)505words[endWordIndex] |= lastWordMask;506}507508checkInvariants();509}510511/**512* Sets the bits from the specified {@code fromIndex} (inclusive) to the513* specified {@code toIndex} (exclusive) to the specified value.514*515* @param fromIndex index of the first bit to be set516* @param toIndex index after the last bit to be set517* @param value value to set the selected bits to518* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,519* or {@code toIndex} is negative, or {@code fromIndex} is520* larger than {@code toIndex}521* @since 1.4522*/523public void set(int fromIndex, int toIndex, boolean value) {524if (value)525set(fromIndex, toIndex);526else527clear(fromIndex, toIndex);528}529530/**531* Sets the bit specified by the index to {@code false}.532*533* @param bitIndex the index of the bit to be cleared534* @throws IndexOutOfBoundsException if the specified index is negative535* @since JDK1.0536*/537public void clear(int bitIndex) {538if (bitIndex < 0)539throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);540541int wordIndex = wordIndex(bitIndex);542if (wordIndex >= wordsInUse)543return;544545words[wordIndex] &= ~(1L << bitIndex);546547recalculateWordsInUse();548checkInvariants();549}550551/**552* Sets the bits from the specified {@code fromIndex} (inclusive) to the553* specified {@code toIndex} (exclusive) to {@code false}.554*555* @param fromIndex index of the first bit to be cleared556* @param toIndex index after the last bit to be cleared557* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,558* or {@code toIndex} is negative, or {@code fromIndex} is559* larger than {@code toIndex}560* @since 1.4561*/562public void clear(int fromIndex, int toIndex) {563checkRange(fromIndex, toIndex);564565if (fromIndex == toIndex)566return;567568int startWordIndex = wordIndex(fromIndex);569if (startWordIndex >= wordsInUse)570return;571572int endWordIndex = wordIndex(toIndex - 1);573if (endWordIndex >= wordsInUse) {574toIndex = length();575endWordIndex = wordsInUse - 1;576}577578long firstWordMask = WORD_MASK << fromIndex;579long lastWordMask = WORD_MASK >>> -toIndex;580if (startWordIndex == endWordIndex) {581// Case 1: One word582words[startWordIndex] &= ~(firstWordMask & lastWordMask);583} else {584// Case 2: Multiple words585// Handle first word586words[startWordIndex] &= ~firstWordMask;587588// Handle intermediate words, if any589for (int i = startWordIndex+1; i < endWordIndex; i++)590words[i] = 0;591592// Handle last word593words[endWordIndex] &= ~lastWordMask;594}595596recalculateWordsInUse();597checkInvariants();598}599600/**601* Sets all of the bits in this BitSet to {@code false}.602*603* @since 1.4604*/605public void clear() {606while (wordsInUse > 0)607words[--wordsInUse] = 0;608}609610/**611* Returns the value of the bit with the specified index. The value612* is {@code true} if the bit with the index {@code bitIndex}613* is currently set in this {@code BitSet}; otherwise, the result614* is {@code false}.615*616* @param bitIndex the bit index617* @return the value of the bit with the specified index618* @throws IndexOutOfBoundsException if the specified index is negative619*/620public boolean get(int bitIndex) {621if (bitIndex < 0)622throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);623624checkInvariants();625626int wordIndex = wordIndex(bitIndex);627return (wordIndex < wordsInUse)628&& ((words[wordIndex] & (1L << bitIndex)) != 0);629}630631/**632* Returns a new {@code BitSet} composed of bits from this {@code BitSet}633* from {@code fromIndex} (inclusive) to {@code toIndex} (exclusive).634*635* @param fromIndex index of the first bit to include636* @param toIndex index after the last bit to include637* @return a new {@code BitSet} from a range of this {@code BitSet}638* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,639* or {@code toIndex} is negative, or {@code fromIndex} is640* larger than {@code toIndex}641* @since 1.4642*/643public BitSet get(int fromIndex, int toIndex) {644checkRange(fromIndex, toIndex);645646checkInvariants();647648int len = length();649650// If no set bits in range return empty bitset651if (len <= fromIndex || fromIndex == toIndex)652return new BitSet(0);653654// An optimization655if (toIndex > len)656toIndex = len;657658BitSet result = new BitSet(toIndex - fromIndex);659int targetWords = wordIndex(toIndex - fromIndex - 1) + 1;660int sourceIndex = wordIndex(fromIndex);661boolean wordAligned = ((fromIndex & BIT_INDEX_MASK) == 0);662663// Process all words but the last word664for (int i = 0; i < targetWords - 1; i++, sourceIndex++)665result.words[i] = wordAligned ? words[sourceIndex] :666(words[sourceIndex] >>> fromIndex) |667(words[sourceIndex+1] << -fromIndex);668669// Process the last word670long lastWordMask = WORD_MASK >>> -toIndex;671result.words[targetWords - 1] =672((toIndex-1) & BIT_INDEX_MASK) < (fromIndex & BIT_INDEX_MASK)673? /* straddles source words */674((words[sourceIndex] >>> fromIndex) |675(words[sourceIndex+1] & lastWordMask) << -fromIndex)676:677((words[sourceIndex] & lastWordMask) >>> fromIndex);678679// Set wordsInUse correctly680result.wordsInUse = targetWords;681result.recalculateWordsInUse();682result.checkInvariants();683684return result;685}686687/**688* Returns the index of the first bit that is set to {@code true}689* that occurs on or after the specified starting index. If no such690* bit exists then {@code -1} is returned.691*692* <p>To iterate over the {@code true} bits in a {@code BitSet},693* use the following loop:694*695* <pre> {@code696* for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {697* // operate on index i here698* if (i == Integer.MAX_VALUE) {699* break; // or (i+1) would overflow700* }701* }}</pre>702*703* @param fromIndex the index to start checking from (inclusive)704* @return the index of the next set bit, or {@code -1} if there705* is no such bit706* @throws IndexOutOfBoundsException if the specified index is negative707* @since 1.4708*/709public int nextSetBit(int fromIndex) {710if (fromIndex < 0)711throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);712713checkInvariants();714715int u = wordIndex(fromIndex);716if (u >= wordsInUse)717return -1;718719long word = words[u] & (WORD_MASK << fromIndex);720721while (true) {722if (word != 0)723return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);724if (++u == wordsInUse)725return -1;726word = words[u];727}728}729730/**731* Returns the index of the first bit that is set to {@code false}732* that occurs on or after the specified starting index.733*734* @param fromIndex the index to start checking from (inclusive)735* @return the index of the next clear bit736* @throws IndexOutOfBoundsException if the specified index is negative737* @since 1.4738*/739public int nextClearBit(int fromIndex) {740// Neither spec nor implementation handle bitsets of maximal length.741// See 4816253.742if (fromIndex < 0)743throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);744745checkInvariants();746747int u = wordIndex(fromIndex);748if (u >= wordsInUse)749return fromIndex;750751long word = ~words[u] & (WORD_MASK << fromIndex);752753while (true) {754if (word != 0)755return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);756if (++u == wordsInUse)757return wordsInUse * BITS_PER_WORD;758word = ~words[u];759}760}761762/**763* Returns the index of the nearest bit that is set to {@code true}764* that occurs on or before the specified starting index.765* If no such bit exists, or if {@code -1} is given as the766* starting index, then {@code -1} is returned.767*768* <p>To iterate over the {@code true} bits in a {@code BitSet},769* use the following loop:770*771* <pre> {@code772* for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {773* // operate on index i here774* }}</pre>775*776* @param fromIndex the index to start checking from (inclusive)777* @return the index of the previous set bit, or {@code -1} if there778* is no such bit779* @throws IndexOutOfBoundsException if the specified index is less780* than {@code -1}781* @since 1.7782*/783public int previousSetBit(int fromIndex) {784if (fromIndex < 0) {785if (fromIndex == -1)786return -1;787throw new IndexOutOfBoundsException(788"fromIndex < -1: " + fromIndex);789}790791checkInvariants();792793int u = wordIndex(fromIndex);794if (u >= wordsInUse)795return length() - 1;796797long word = words[u] & (WORD_MASK >>> -(fromIndex+1));798799while (true) {800if (word != 0)801return (u+1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word);802if (u-- == 0)803return -1;804word = words[u];805}806}807808/**809* Returns the index of the nearest bit that is set to {@code false}810* that occurs on or before the specified starting index.811* If no such bit exists, or if {@code -1} is given as the812* starting index, then {@code -1} is returned.813*814* @param fromIndex the index to start checking from (inclusive)815* @return the index of the previous clear bit, or {@code -1} if there816* is no such bit817* @throws IndexOutOfBoundsException if the specified index is less818* than {@code -1}819* @since 1.7820*/821public int previousClearBit(int fromIndex) {822if (fromIndex < 0) {823if (fromIndex == -1)824return -1;825throw new IndexOutOfBoundsException(826"fromIndex < -1: " + fromIndex);827}828829checkInvariants();830831int u = wordIndex(fromIndex);832if (u >= wordsInUse)833return fromIndex;834835long word = ~words[u] & (WORD_MASK >>> -(fromIndex+1));836837while (true) {838if (word != 0)839return (u+1) * BITS_PER_WORD -1 - Long.numberOfLeadingZeros(word);840if (u-- == 0)841return -1;842word = ~words[u];843}844}845846/**847* Returns the "logical size" of this {@code BitSet}: the index of848* the highest set bit in the {@code BitSet} plus one. Returns zero849* if the {@code BitSet} contains no set bits.850*851* @return the logical size of this {@code BitSet}852* @since 1.2853*/854public int length() {855if (wordsInUse == 0)856return 0;857858return BITS_PER_WORD * (wordsInUse - 1) +859(BITS_PER_WORD - Long.numberOfLeadingZeros(words[wordsInUse - 1]));860}861862/**863* Returns true if this {@code BitSet} contains no bits that are set864* to {@code true}.865*866* @return boolean indicating whether this {@code BitSet} is empty867* @since 1.4868*/869public boolean isEmpty() {870return wordsInUse == 0;871}872873/**874* Returns true if the specified {@code BitSet} has any bits set to875* {@code true} that are also set to {@code true} in this {@code BitSet}.876*877* @param set {@code BitSet} to intersect with878* @return boolean indicating whether this {@code BitSet} intersects879* the specified {@code BitSet}880* @since 1.4881*/882public boolean intersects(BitSet set) {883for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)884if ((words[i] & set.words[i]) != 0)885return true;886return false;887}888889/**890* Returns the number of bits set to {@code true} in this {@code BitSet}.891*892* @return the number of bits set to {@code true} in this {@code BitSet}893* @since 1.4894*/895public int cardinality() {896int sum = 0;897for (int i = 0; i < wordsInUse; i++)898sum += Long.bitCount(words[i]);899return sum;900}901902/**903* Performs a logical <b>AND</b> of this target bit set with the904* argument bit set. This bit set is modified so that each bit in it905* has the value {@code true} if and only if it both initially906* had the value {@code true} and the corresponding bit in the907* bit set argument also had the value {@code true}.908*909* @param set a bit set910*/911public void and(BitSet set) {912if (this == set)913return;914915while (wordsInUse > set.wordsInUse)916words[--wordsInUse] = 0;917918// Perform logical AND on words in common919for (int i = 0; i < wordsInUse; i++)920words[i] &= set.words[i];921922recalculateWordsInUse();923checkInvariants();924}925926/**927* Performs a logical <b>OR</b> of this bit set with the bit set928* argument. This bit set is modified so that a bit in it has the929* value {@code true} if and only if it either already had the930* value {@code true} or the corresponding bit in the bit set931* argument has the value {@code true}.932*933* @param set a bit set934*/935public void or(BitSet set) {936if (this == set)937return;938939int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);940941if (wordsInUse < set.wordsInUse) {942ensureCapacity(set.wordsInUse);943wordsInUse = set.wordsInUse;944}945946// Perform logical OR on words in common947for (int i = 0; i < wordsInCommon; i++)948words[i] |= set.words[i];949950// Copy any remaining words951if (wordsInCommon < set.wordsInUse)952System.arraycopy(set.words, wordsInCommon,953words, wordsInCommon,954wordsInUse - wordsInCommon);955956// recalculateWordsInUse() is unnecessary957checkInvariants();958}959960/**961* Performs a logical <b>XOR</b> of this bit set with the bit set962* argument. This bit set is modified so that a bit in it has the963* value {@code true} if and only if one of the following964* statements holds:965* <ul>966* <li>The bit initially has the value {@code true}, and the967* corresponding bit in the argument has the value {@code false}.968* <li>The bit initially has the value {@code false}, and the969* corresponding bit in the argument has the value {@code true}.970* </ul>971*972* @param set a bit set973*/974public void xor(BitSet set) {975int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);976977if (wordsInUse < set.wordsInUse) {978ensureCapacity(set.wordsInUse);979wordsInUse = set.wordsInUse;980}981982// Perform logical XOR on words in common983for (int i = 0; i < wordsInCommon; i++)984words[i] ^= set.words[i];985986// Copy any remaining words987if (wordsInCommon < set.wordsInUse)988System.arraycopy(set.words, wordsInCommon,989words, wordsInCommon,990set.wordsInUse - wordsInCommon);991992recalculateWordsInUse();993checkInvariants();994}995996/**997* Clears all of the bits in this {@code BitSet} whose corresponding998* bit is set in the specified {@code BitSet}.999*1000* @param set the {@code BitSet} with which to mask this1001* {@code BitSet}1002* @since 1.21003*/1004public void andNot(BitSet set) {1005// Perform logical (a & !b) on words in common1006for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)1007words[i] &= ~set.words[i];10081009recalculateWordsInUse();1010checkInvariants();1011}10121013/**1014* Returns the hash code value for this bit set. The hash code depends1015* only on which bits are set within this {@code BitSet}.1016*1017* <p>The hash code is defined to be the result of the following1018* calculation:1019* <pre> {@code1020* public int hashCode() {1021* long h = 1234;1022* long[] words = toLongArray();1023* for (int i = words.length; --i >= 0; )1024* h ^= words[i] * (i + 1);1025* return (int)((h >> 32) ^ h);1026* }}</pre>1027* Note that the hash code changes if the set of bits is altered.1028*1029* @return the hash code value for this bit set1030*/1031public int hashCode() {1032long h = 1234;1033for (int i = wordsInUse; --i >= 0; )1034h ^= words[i] * (i + 1);10351036return (int)((h >> 32) ^ h);1037}10381039/**1040* Returns the number of bits of space actually in use by this1041* {@code BitSet} to represent bit values.1042* The maximum element in the set is the size - 1st element.1043*1044* @return the number of bits currently in this bit set1045*/1046public int size() {1047return words.length * BITS_PER_WORD;1048}10491050/**1051* Compares this object against the specified object.1052* The result is {@code true} if and only if the argument is1053* not {@code null} and is a {@code Bitset} object that has1054* exactly the same set of bits set to {@code true} as this bit1055* set. That is, for every nonnegative {@code int} index {@code k},1056* <pre>((BitSet)obj).get(k) == this.get(k)</pre>1057* must be true. The current sizes of the two bit sets are not compared.1058*1059* @param obj the object to compare with1060* @return {@code true} if the objects are the same;1061* {@code false} otherwise1062* @see #size()1063*/1064public boolean equals(Object obj) {1065if (!(obj instanceof BitSet))1066return false;1067if (this == obj)1068return true;10691070BitSet set = (BitSet) obj;10711072checkInvariants();1073set.checkInvariants();10741075if (wordsInUse != set.wordsInUse)1076return false;10771078// Check words in use by both BitSets1079for (int i = 0; i < wordsInUse; i++)1080if (words[i] != set.words[i])1081return false;10821083return true;1084}10851086/**1087* Cloning this {@code BitSet} produces a new {@code BitSet}1088* that is equal to it.1089* The clone of the bit set is another bit set that has exactly the1090* same bits set to {@code true} as this bit set.1091*1092* @return a clone of this bit set1093* @see #size()1094*/1095public Object clone() {1096if (! sizeIsSticky)1097trimToSize();10981099try {1100BitSet result = (BitSet) super.clone();1101result.words = words.clone();1102result.checkInvariants();1103return result;1104} catch (CloneNotSupportedException e) {1105throw new InternalError(e);1106}1107}11081109/**1110* Attempts to reduce internal storage used for the bits in this bit set.1111* Calling this method may, but is not required to, affect the value1112* returned by a subsequent call to the {@link #size()} method.1113*/1114private void trimToSize() {1115if (wordsInUse != words.length) {1116words = Arrays.copyOf(words, wordsInUse);1117checkInvariants();1118}1119}11201121/**1122* Save the state of the {@code BitSet} instance to a stream (i.e.,1123* serialize it).1124*/1125private void writeObject(ObjectOutputStream s)1126throws IOException {11271128checkInvariants();11291130if (! sizeIsSticky)1131trimToSize();11321133ObjectOutputStream.PutField fields = s.putFields();1134fields.put("bits", words);1135s.writeFields();1136}11371138/**1139* Reconstitute the {@code BitSet} instance from a stream (i.e.,1140* deserialize it).1141*/1142private void readObject(ObjectInputStream s)1143throws IOException, ClassNotFoundException {11441145ObjectInputStream.GetField fields = s.readFields();1146words = (long[]) fields.get("bits", null);11471148// Assume maximum length then find real length1149// because recalculateWordsInUse assumes maintenance1150// or reduction in logical size1151wordsInUse = words.length;1152recalculateWordsInUse();1153sizeIsSticky = (words.length > 0 && words[words.length-1] == 0L); // heuristic1154checkInvariants();1155}11561157/**1158* Returns a string representation of this bit set. For every index1159* for which this {@code BitSet} contains a bit in the set1160* state, the decimal representation of that index is included in1161* the result. Such indices are listed in order from lowest to1162* highest, separated by ", " (a comma and a space) and1163* surrounded by braces, resulting in the usual mathematical1164* notation for a set of integers.1165*1166* <p>Example:1167* <pre>1168* BitSet drPepper = new BitSet();</pre>1169* Now {@code drPepper.toString()} returns "{@code {}}".1170* <pre>1171* drPepper.set(2);</pre>1172* Now {@code drPepper.toString()} returns "{@code {2}}".1173* <pre>1174* drPepper.set(4);1175* drPepper.set(10);</pre>1176* Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}".1177*1178* @return a string representation of this bit set1179*/1180public String toString() {1181checkInvariants();11821183int numBits = (wordsInUse > 128) ?1184cardinality() : wordsInUse * BITS_PER_WORD;1185StringBuilder b = new StringBuilder(6*numBits + 2);1186b.append('{');11871188int i = nextSetBit(0);1189if (i != -1) {1190b.append(i);1191while (true) {1192if (++i < 0) break;1193if ((i = nextSetBit(i)) < 0) break;1194int endOfRun = nextClearBit(i);1195do { b.append(", ").append(i); }1196while (++i != endOfRun);1197}1198}11991200b.append('}');1201return b.toString();1202}12031204/**1205* Returns a stream of indices for which this {@code BitSet}1206* contains a bit in the set state. The indices are returned1207* in order, from lowest to highest. The size of the stream1208* is the number of bits in the set state, equal to the value1209* returned by the {@link #cardinality()} method.1210*1211* <p>The bit set must remain constant during the execution of the1212* terminal stream operation. Otherwise, the result of the terminal1213* stream operation is undefined.1214*1215* @return a stream of integers representing set indices1216* @since 1.81217*/1218public IntStream stream() {1219class BitSetIterator implements PrimitiveIterator.OfInt {1220int next = nextSetBit(0);12211222@Override1223public boolean hasNext() {1224return next != -1;1225}12261227@Override1228public int nextInt() {1229if (next != -1) {1230int ret = next;1231next = nextSetBit(next+1);1232return ret;1233} else {1234throw new NoSuchElementException();1235}1236}1237}12381239return StreamSupport.intStream(1240() -> Spliterators.spliterator(1241new BitSetIterator(), cardinality(),1242Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED),1243Spliterator.SIZED | Spliterator.SUBSIZED |1244Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED,1245false);1246}1247}124812491250