/** *SetsthefieldwordsInUsetothelogicalsizeinwordsofthebitset. *WARNING:Thismethodassumesthatthenumberofwordsactuallyinuseis *lessthanorequaltothecurrentvalueofwordsInUse!
*/ privatevoid recalculateWordsInUse() { // Traverse the bitset until a used word is found int i; for (i = wordsInUse-1; i >= 0; i--) if (words[i] != 0) break;
/** *Returnsanewbytearraycontainingallthebitsinthisbitset. * *<p>Moreprecisely,if *<br>{@codebyte[]bytes=s.toByteArray();} *<br>then{@codebytes.length==(s.length()+7)/8}and *<br>{@codes.get(n)==((bytes[n/8]&(1<<(n%8)))!=0)} *<br>forall{@coden<8*bytes.length}. * *@returnabytearraycontainingalittle-endianrepresentation *ofallthebitsinthisbitset *@since1.7
*/ publicbyte[] toByteArray() { int n = wordsInUse; if (n == 0) returnnewbyte[0]; int len = 8 * (n-1); for (long x = words[n - 1]; x != 0; x >>>= 8)
len++; byte[] bytes = newbyte[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;
}
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;
}
// Increase capacity if necessary 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 (restores invariants)
words[endWordIndex] |= lastWordMask;
}
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;
}
// If no set bits in range return empty bitset if (len <= fromIndex || fromIndex == toIndex) returnnew 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;
result.words[targetWords - 1] =
((toIndex-1) & BIT_INDEX_MASK) < (fromIndex & BIT_INDEX_MASK)
? /* straddles source words */
((words[sourceIndex] >>> fromIndex) |
(words[sourceIndex+1] & lastWordMask) << -fromIndex)
:
((words[sourceIndex] & lastWordMask) >>> fromIndex);
// Set wordsInUse correctly
result.wordsInUse = targetWords;
result.recalculateWordsInUse();
result.checkInvariants();
return result;
}
/** *Returnstheindexofthefirstbitthatissetto{@codetrue} *thatoccursonorafterthespecifiedstartingindex.Ifnosuch *bitexiststhen{@code-1}isreturned. * *<p>Toiterateoverthe{@codetrue}bitsina{@codeBitSet}, *usethefollowingloop: * *<pre>{@code *for(inti=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> * *@paramfromIndextheindextostartcheckingfrom(inclusive) *@returntheindexofthenextsetbit,or{@code-1}ifthere *isnosuchbit *@throwsIndexOutOfBoundsExceptionifthespecifiedindexisnegative *@since1.4
*/ publicint nextSetBit(int fromIndex) { if (fromIndex < 0) thrownew 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];
}
}
/** *Returnstheindexofthefirstbitthatissetto{@codefalse} *thatoccursonorafterthespecifiedstartingindex. * *@paramfromIndextheindextostartcheckingfrom(inclusive) *@returntheindexofthenextclearbit *@throwsIndexOutOfBoundsExceptionifthespecifiedindexisnegative *@since1.4
*/ publicint nextClearBit(int fromIndex) { // Neither spec nor implementation handle bitsets of maximal length. // See 4816253. if (fromIndex < 0) thrownew 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];
}
}
/** *Returnstheindexofthenearestbitthatissetto{@codetrue} *thatoccursonorbeforethespecifiedstartingindex. *Ifnosuchbitexists,orif{@code-1}isgivenasthe *startingindex,then{@code-1}isreturned. * *<p>Toiterateoverthe{@codetrue}bitsina{@codeBitSet}, *usethefollowingloop: * *<pre>{@code *for(inti=bs.length();(i=bs.previousSetBit(i-1))>=0;){ *// operate on index i here *}}</pre> * *@paramfromIndextheindextostartcheckingfrom(inclusive) *@returntheindexoftheprevioussetbit,or{@code-1}ifthere *isnosuchbit *@throwsIndexOutOfBoundsExceptionifthespecifiedindexisless *than{@code-1} *@since1.7
*/ publicint previousSetBit(int fromIndex) { if (fromIndex < 0) { if (fromIndex == -1) return -1; thrownew 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];
}
}
/** *Returnstrueifthespecified{@codeBitSet}hasanybitssetto *{@codetrue}thatarealsosetto{@codetrue}inthis{@codeBitSet}. * *@paramset{@codeBitSet}tointersectwith *@returnbooleanindicatingwhetherthis{@codeBitSet}intersects *thespecified{@codeBitSet} *@since1.4
*/ publicboolean intersects(BitSet set) { for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--) if ((words[i] & set.words[i]) != 0) returntrue; returnfalse;
}
/** *Returnsthenumberofbitssetto{@codetrue}inthis{@codeBitSet}. * *@returnthenumberofbitssetto{@codetrue}inthis{@codeBitSet} *@since1.4
*/ publicint cardinality() { int sum = 0; for (int i = 0; i < wordsInUse; i++)
sum += Long.bitCount(words[i]); return sum;
}
if (wordsInUse < set.wordsInUse) {
ensureCapacity(set.wordsInUse);
wordsInUse = set.wordsInUse;
}
// Perform logical XOR on words in common for (int i = 0; i < wordsInCommon; i++)
words[i] ^= set.words[i];
// Copy any remaining words if (wordsInCommon < set.wordsInUse)
System.arraycopy(set.words, wordsInCommon,
words, wordsInCommon,
set.wordsInUse - wordsInCommon);
recalculateWordsInUse();
checkInvariants();
}
/** *Clearsallofthebitsinthis{@codeBitSet}whosecorresponding *bitissetinthespecified{@codeBitSet}. * *@paramsetthe{@codeBitSet}withwhichtomaskthis *{@codeBitSet} *@since1.2
*/ publicvoid andNot(BitSet set) { // Perform logical (a & !b) on words in common for (int i = Math.min(wordsInUse, set.wordsInUse) - 1; i >= 0; i--)
words[i] &= ~set.words[i];
recalculateWordsInUse();
checkInvariants();
}
/** *Returnsthehashcodevalueforthisbitset.Thehashcodedepends *onlyonwhichbitsaresetwithinthis{@codeBitSet}. * *<p>Thehashcodeisdefinedtobetheresultofthefollowing *calculation: *<pre>{@code *publicinthashCode(){ *longh=1234; *long[]words=toLongArray(); *for(inti=words.length;--i>=0;) *h^=words[i]*(i+1); *return(int)((h>>32)^h); *}}</pre> *Notethatthehashcodechangesifthesetofbitsisaltered. * *@returnthehashcodevalueforthisbitset
*/ publicint hashCode() { long h = 1234; for (int i = wordsInUse; --i >= 0; )
h ^= words[i] * (i + 1);
finalint MAX_INITIAL_CAPACITY = Integer.MAX_VALUE - 8; int numBits = (wordsInUse > 128) ?
cardinality() : wordsInUse * BITS_PER_WORD; // Avoid overflow in the case of a humongous numBits int initialCapacity = (numBits <= (MAX_INITIAL_CAPACITY - 2) / 6) ? 6 * numBits + 2 : MAX_INITIAL_CAPACITY;
StringBuilder b = new StringBuilder(initialCapacity);
b.append('{');
int i = nextSetBit(0); if (i != -1) {
b.append(i); while (true) { if (++i < 0) break; if ((i = nextSetBit(i)) < 0) break; int endOfRun = nextClearBit(i); do { b.append(", ").append(i); } while (++i != endOfRun);
}
}
b.append('}'); return b.toString();
}
/** *Returnsastreamofindicesforwhichthis{@codeBitSet} *containsabitinthesetstate.Theindicesarereturned *inorder,fromlowesttohighest.Thesizeofthestream *isthenumberofbitsinthesetstate,equaltothevalue *returnedbythe{@link#cardinality()}method. * *<p>Thestreambindstothisbitsetwhentheterminalstreamoperation *commences(specifically,thespliteratorforthestreamis *<ahref="Spliterator.html#binding"><em>late-binding</em></a>).Ifthe *bitsetismodifiedduringthatoperationthentheresultisundefined. * *@returnastreamofintegersrepresentingsetindices *@since1.8
*/ public IntStream stream() { class BitSetSpliterator implements Spliterator.OfInt { privateint index; // current bit index for a set bit privateint fence; // -1 until used; then one past last bit index privateint est; // size estimate privateboolean root; // true if root and not split // root == true then size estimate is accurate // index == -1 or index >= fence if fully traversed // Special case when the max bit set is Integer.MAX_VALUE
BitSetSpliterator(int origin, int fence, int est, boolean root) { this.index = origin; this.fence = fence; this.est = est; this.root = root;
}
privateint getFence() { int hi; if ((hi = fence) < 0) { // Round up fence to maximum cardinality for allocated words // This is sufficient and cheap for sequential access // When splitting this value is lowered
hi = fence = (wordsInUse >= wordIndex(Integer.MAX_VALUE))
? Integer.MAX_VALUE
: wordsInUse << ADDRESS_BITS_PER_WORD;
est = cardinality();
index = nextSetBit(0);
} return hi;
}
int hi = getFence(); int i = index; if (i < 0 || i >= hi) { // Check if there is a final bit set for Integer.MAX_VALUE if (i == Integer.MAX_VALUE && hi == Integer.MAX_VALUE) {
index = -1;
action.accept(Integer.MAX_VALUE); returntrue;
} returnfalse;
}
int u = wordIndex(i); // next lower word bound int v = wordIndex(hi - 1); // upper word bound
words_loop: for (; u <= v && i <= hi; u++, i = u << ADDRESS_BITS_PER_WORD) { long word = words[u] & (WORD_MASK << i); while (word != 0) {
i = (u << ADDRESS_BITS_PER_WORD) + Long.numberOfTrailingZeros(word); if (i >= hi) { // Break out of outer loop to ensure check of // Integer.MAX_VALUE bit set break words_loop;
}
// Flip the set bit
word &= ~(1L << i);
action.accept(i);
}
}
}
// Check if there is a final bit set for Integer.MAX_VALUE if (i == Integer.MAX_VALUE && hi == Integer.MAX_VALUE) {
action.accept(Integer.MAX_VALUE);
}
}
@Override public OfInt trySplit() { int hi = getFence(); int lo = index; if (lo < 0) { returnnull;
}
// Lower the fence to be the upper bound of last bit set // The index is the first bit set, thus this spliterator // covers one bit and cannot be split, or two or more // bits
hi = fence = (hi < Integer.MAX_VALUE || !get(Integer.MAX_VALUE))
? previousSetBit(hi - 1) + 1
: Integer.MAX_VALUE;
// Find the mid point int mid = (lo + hi) >>> 1; if (lo >= mid) { returnnull;
}
// Raise the index of this spliterator to be the next set bit // from the mid point
index = nextSetBit(mid, wordIndex(hi - 1));
root = false;
// Don't lower the fence (mid point) of the returned spliterator, // traversal or further splitting will do that work returnnew BitSetSpliterator(lo, mid, est >>>= 1, false);
}
@Override publiclong estimateSize() {
getFence(); // force init return est;
}
@Override publicint characteristics() { // Only sized when root and not split return (root ? Spliterator.SIZED : 0) |
Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED;
}
@Override public Comparator<? super Integer> getComparator() { returnnull;
}
} return StreamSupport.intStream(new BitSetSpliterator(0, -1, 0, true), false);
}
/** *Returnstheindexofthefirstbitthatissetto{@codetrue} *thatoccursonorafterthespecifiedstartingindexanduptoand *includingthespecifiedwordindex *Ifnosuchbitexiststhen{@code-1}isreturned. * *@paramfromIndextheindextostartcheckingfrom(inclusive) *@paramtoWordIndexthelastwordindextocheck(inclusive) *@returntheindexofthenextsetbit,or{@code-1}ifthere *isnosuchbit
*/ privateint nextSetBit(int fromIndex, int toWordIndex) { int u = wordIndex(fromIndex); // Check if out of bounds if (u > toWordIndex) return -1;
long word = words[u] & (WORD_MASK << fromIndex);
while (true) { if (word != 0) return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); // Check if out of bounds if (++u > toWordIndex) return -1;
word = words[u];
}
}
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.37 Sekunden
(vorverarbeitet am 2026-06-10)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.