1. /*
  2. * @(#)BitSet.java 1.55 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util;
  8. import java.io.*;
  9. /**
  10. * This class implements a vector of bits that grows as needed. Each
  11. * component of the bit set has a <code>boolean</code> value. The
  12. * bits of a <code>BitSet</code> are indexed by nonnegative integers.
  13. * Individual indexed bits can be examined, set, or cleared. One
  14. * <code>BitSet</code> may be used to modify the contents of another
  15. * <code>BitSet</code> through logical AND, logical inclusive OR, and
  16. * logical exclusive OR operations.
  17. * <p>
  18. * By default, all bits in the set initially have the value
  19. * <code>false</code>.
  20. * <p>
  21. * Every bit set has a current size, which is the number of bits
  22. * of space currently in use by the bit set. Note that the size is
  23. * related to the implementation of a bit set, so it may change with
  24. * implementation. The length of a bit set relates to logical length
  25. * of a bit set and is defined independently of implementation.
  26. * <p>
  27. * Unless otherwise noted, passing a null parameter to any of the
  28. * methods in a <code>BitSet</code> will result in a
  29. * <code>NullPointerException</code>.
  30. *
  31. * A <code>BitSet</code> is not safe for multithreaded use without
  32. * external synchronization.
  33. *
  34. * @author Arthur van Hoff
  35. * @author Michael McCloskey
  36. * @version 1.55, 01/23/03
  37. * @since JDK1.0
  38. */
  39. public class BitSet implements Cloneable, java.io.Serializable {
  40. /*
  41. * BitSets are packed into arrays of "units." Currently a unit is a long,
  42. * which consists of 64 bits, requiring 6 address bits. The choice of unit
  43. * is determined purely by performance concerns.
  44. */
  45. private final static int ADDRESS_BITS_PER_UNIT = 6;
  46. private final static int BITS_PER_UNIT = 1 << ADDRESS_BITS_PER_UNIT;
  47. private final static int BIT_INDEX_MASK = BITS_PER_UNIT - 1;
  48. /* Used to shift left or right for a partial word mask */
  49. private static final long WORD_MASK = 0xffffffffffffffffL;
  50. /**
  51. * The bits in this BitSet. The ith bit is stored in bits[i/64] at
  52. * bit position i % 64 (where bit position 0 refers to the least
  53. * significant bit and 63 refers to the most significant bit).
  54. * INVARIANT: The words in bits[] above unitInUse-1 are zero.
  55. *
  56. * @serial
  57. */
  58. private long bits[]; // this should be called unit[]
  59. /**
  60. * The number of units in the logical size of this BitSet.
  61. * INVARIANT: unitsInUse is nonnegative.
  62. * INVARIANT: bits[unitsInUse-1] is nonzero unless unitsInUse is zero.
  63. */
  64. private transient int unitsInUse = 0;
  65. /* use serialVersionUID from JDK 1.0.2 for interoperability */
  66. private static final long serialVersionUID = 7997698588986878753L;
  67. /**
  68. * Given a bit index return unit index containing it.
  69. */
  70. private static int unitIndex(int bitIndex) {
  71. return bitIndex >> ADDRESS_BITS_PER_UNIT;
  72. }
  73. /**
  74. * Given a bit index, return a unit that masks that bit in its unit.
  75. */
  76. private static long bit(int bitIndex) {
  77. return 1L << (bitIndex & BIT_INDEX_MASK);
  78. }
  79. /**
  80. * Set the field unitsInUse with the logical size in units of the bit
  81. * set. WARNING:This function assumes that the number of units actually
  82. * in use is less than or equal to the current value of unitsInUse!
  83. */
  84. private void recalculateUnitsInUse() {
  85. // Traverse the bitset until a used unit is found
  86. int i;
  87. for (i = unitsInUse-1; i >= 0; i--)
  88. if(bits[i] != 0)
  89. break;
  90. unitsInUse = i+1; // The new logical size
  91. }
  92. /**
  93. * Creates a new bit set. All bits are initially <code>false</code>.
  94. */
  95. public BitSet() {
  96. this(BITS_PER_UNIT);
  97. }
  98. /**
  99. * Creates a bit set whose initial size is large enough to explicitly
  100. * represent bits with indices in the range <code>0</code> through
  101. * <code>nbits-1</code>. All bits are initially <code>false</code>.
  102. *
  103. * @param nbits the initial size of the bit set.
  104. * @exception NegativeArraySizeException if the specified initial size
  105. * is negative.
  106. */
  107. public BitSet(int nbits) {
  108. // nbits can't be negative; size 0 is OK
  109. if (nbits < 0)
  110. throw new NegativeArraySizeException("nbits < 0: " + nbits);
  111. bits = new long[(unitIndex(nbits-1) + 1)];
  112. }
  113. /**
  114. * Ensures that the BitSet can hold enough units.
  115. * @param unitsRequired the minimum acceptable number of units.
  116. */
  117. private void ensureCapacity(int unitsRequired) {
  118. if (bits.length < unitsRequired) {
  119. // Allocate larger of doubled size or required size
  120. int request = Math.max(2 * bits.length, unitsRequired);
  121. long newBits[] = new long[request];
  122. System.arraycopy(bits, 0, newBits, 0, unitsInUse);
  123. bits = newBits;
  124. }
  125. }
  126. /**
  127. * Sets the bit at the specified index to to the complement of its
  128. * current value.
  129. *
  130. * @param bitIndex the index of the bit to flip.
  131. * @exception IndexOutOfBoundsException if the specified index is negative.
  132. * @since 1.4
  133. */
  134. public void flip(int bitIndex) {
  135. if (bitIndex < 0)
  136. throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
  137. int unitIndex = unitIndex(bitIndex);
  138. int unitsRequired = unitIndex+1;
  139. if (unitsInUse < unitsRequired) {
  140. ensureCapacity(unitsRequired);
  141. bits[unitIndex] ^= bit(bitIndex);
  142. unitsInUse = unitsRequired;
  143. } else {
  144. bits[unitIndex] ^= bit(bitIndex);
  145. if (bits[unitsInUse-1] == 0)
  146. recalculateUnitsInUse();
  147. }
  148. }
  149. /**
  150. * Sets each bit from the specified fromIndex(inclusive) to the
  151. * specified toIndex(exclusive) to the complement of its current
  152. * value.
  153. *
  154. * @param fromIndex index of the first bit to flip.
  155. * @param toIndex index after the last bit to flip.
  156. * @exception IndexOutOfBoundsException if <tt>fromIndex</tt> is negative,
  157. * or <tt>toIndex</tt> is negative, or <tt>fromIndex</tt> is
  158. * larger than <tt>toIndex</tt>.
  159. * @since 1.4
  160. */
  161. public void flip(int fromIndex, int toIndex) {
  162. if (fromIndex < 0)
  163. throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
  164. if (toIndex < 0)
  165. throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex);
  166. if (fromIndex > toIndex)
  167. throw new IndexOutOfBoundsException("fromIndex: " + fromIndex +
  168. " > toIndex: " + toIndex);
  169. // Increase capacity if necessary
  170. int endUnitIndex = unitIndex(toIndex);
  171. int unitsRequired = endUnitIndex + 1;
  172. if (unitsInUse < unitsRequired) {
  173. ensureCapacity(unitsRequired);
  174. unitsInUse = unitsRequired;
  175. }
  176. int startUnitIndex = unitIndex(fromIndex);
  177. long bitMask = 0;
  178. if (startUnitIndex == endUnitIndex) {
  179. // Case 1: One word
  180. bitMask = (1L << (toIndex & BIT_INDEX_MASK)) -
  181. (1L << (fromIndex & BIT_INDEX_MASK));
  182. bits[startUnitIndex] ^= bitMask;
  183. if (bits[unitsInUse-1] == 0)
  184. recalculateUnitsInUse();
  185. return;
  186. }
  187. // Case 2: Multiple words
  188. // Handle first word
  189. bitMask = bitsLeftOf(fromIndex & BIT_INDEX_MASK);
  190. bits[startUnitIndex] ^= bitMask;
  191. // Handle intermediate words, if any
  192. if (endUnitIndex - startUnitIndex > 1) {
  193. for(int i=startUnitIndex+1; i<endUnitIndex; i++)
  194. bits[i] ^= WORD_MASK;
  195. }
  196. // Handle last word
  197. bitMask = bitsRightOf(toIndex & BIT_INDEX_MASK);
  198. bits[endUnitIndex] ^= bitMask;
  199. // Check to see if we reduced size
  200. if (bits[unitsInUse-1] == 0)
  201. recalculateUnitsInUse();
  202. }
  203. /**
  204. * Returns a long that has all bits that are less significant
  205. * than the specified index set to 1. All other bits are 0.
  206. */
  207. private static long bitsRightOf(int x) {
  208. return (x==0 ? 0 : WORD_MASK >>> (64-x));
  209. }
  210. /**
  211. * Returns a long that has all the bits that are more significant
  212. * than or equal to the specified index set to 1. All other bits are 0.
  213. */
  214. private static long bitsLeftOf(int x) {
  215. return WORD_MASK << x;
  216. }
  217. /**
  218. * Sets the bit at the specified index to <code>true</code>.
  219. *
  220. * @param bitIndex a bit index.
  221. * @exception IndexOutOfBoundsException if the specified index is negative.
  222. * @since JDK1.0
  223. */
  224. public void set(int bitIndex) {
  225. if (bitIndex < 0)
  226. throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
  227. int unitIndex = unitIndex(bitIndex);
  228. int unitsRequired = unitIndex + 1;
  229. if (unitsInUse < unitsRequired) {
  230. ensureCapacity(unitsRequired);
  231. bits[unitIndex] |= bit(bitIndex);
  232. unitsInUse = unitsRequired;
  233. } else {
  234. bits[unitIndex] |= bit(bitIndex);
  235. }
  236. }
  237. /**
  238. * Sets the bit at the specified index to the specified value.
  239. *
  240. * @param bitIndex a bit index.
  241. * @param value a boolean value to set.
  242. * @exception IndexOutOfBoundsException if the specified index is negative.
  243. * @since 1.4
  244. */
  245. public void set(int bitIndex, boolean value) {
  246. if (value)
  247. set(bitIndex);
  248. else
  249. clear(bitIndex);
  250. }
  251. /**
  252. * Sets the bits from the specified fromIndex(inclusive) to the
  253. * specified toIndex(exclusive) to <code>true</code>.
  254. *
  255. * @param fromIndex index of the first bit to be set.
  256. * @param toIndex index after the last bit to be set.
  257. * @exception IndexOutOfBoundsException if <tt>fromIndex</tt> is negative,
  258. * or <tt>toIndex</tt> is negative, or <tt>fromIndex</tt> is
  259. * larger than <tt>toIndex</tt>.
  260. * @since 1.4
  261. */
  262. public void set(int fromIndex, int toIndex) {
  263. if (fromIndex < 0)
  264. throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
  265. if (toIndex < 0)
  266. throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex);
  267. if (fromIndex > toIndex)
  268. throw new IndexOutOfBoundsException("fromIndex: " + fromIndex +
  269. " > toIndex: " + toIndex);
  270. // Increase capacity if necessary
  271. int endUnitIndex = unitIndex(toIndex);
  272. int unitsRequired = endUnitIndex + 1;
  273. if (unitsInUse < unitsRequired) {
  274. ensureCapacity(unitsRequired);
  275. unitsInUse = unitsRequired;
  276. }
  277. int startUnitIndex = unitIndex(fromIndex);
  278. long bitMask = 0;
  279. if (startUnitIndex == endUnitIndex) {
  280. // Case 1: One word
  281. bitMask = (1L << (toIndex & BIT_INDEX_MASK)) -
  282. (1L << (fromIndex & BIT_INDEX_MASK));
  283. bits[startUnitIndex] |= bitMask;
  284. return;
  285. }
  286. // Case 2: Multiple words
  287. // Handle first word
  288. bitMask = bitsLeftOf(fromIndex & BIT_INDEX_MASK);
  289. bits[startUnitIndex] |= bitMask;
  290. // Handle intermediate words, if any
  291. if (endUnitIndex - startUnitIndex > 1) {
  292. for(int i=startUnitIndex+1; i<endUnitIndex; i++)
  293. bits[i] |= WORD_MASK;
  294. }
  295. // Handle last word
  296. bitMask = bitsRightOf(toIndex & BIT_INDEX_MASK);
  297. bits[endUnitIndex] |= bitMask;
  298. }
  299. /**
  300. * Sets the bits from the specified fromIndex(inclusive) to the
  301. * specified toIndex(exclusive) to the specified value.
  302. *
  303. * @param fromIndex index of the first bit to be set.
  304. * @param toIndex index after the last bit to be set
  305. * @param value value to set the selected bits to
  306. * @exception IndexOutOfBoundsException if <tt>fromIndex</tt> is negative,
  307. * or <tt>toIndex</tt> is negative, or <tt>fromIndex</tt> is
  308. * larger than <tt>toIndex</tt>.
  309. * @since 1.4
  310. */
  311. public void set(int fromIndex, int toIndex, boolean value) {
  312. if (value)
  313. set(fromIndex, toIndex);
  314. else
  315. clear(fromIndex, toIndex);
  316. }
  317. /**
  318. * Sets the bit specified by the index to <code>false</code>.
  319. *
  320. * @param bitIndex the index of the bit to be cleared.
  321. * @exception IndexOutOfBoundsException if the specified index is negative.
  322. * @since JDK1.0
  323. */
  324. public void clear(int bitIndex) {
  325. if (bitIndex < 0)
  326. throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
  327. int unitIndex = unitIndex(bitIndex);
  328. if (unitIndex >= unitsInUse)
  329. return;
  330. bits[unitIndex] &= ~bit(bitIndex);
  331. if (bits[unitsInUse-1] == 0)
  332. recalculateUnitsInUse();
  333. }
  334. /**
  335. * Sets the bits from the specified fromIndex(inclusive) to the
  336. * specified toIndex(exclusive) to <code>false</code>.
  337. *
  338. * @param fromIndex index of the first bit to be cleared.
  339. * @param toIndex index after the last bit to be cleared.
  340. * @exception IndexOutOfBoundsException if <tt>fromIndex</tt> is negative,
  341. * or <tt>toIndex</tt> is negative, or <tt>fromIndex</tt> is
  342. * larger than <tt>toIndex</tt>.
  343. * @since 1.4
  344. */
  345. public void clear(int fromIndex, int toIndex) {
  346. if (fromIndex < 0)
  347. throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
  348. if (toIndex < 0)
  349. throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex);
  350. if (fromIndex > toIndex)
  351. throw new IndexOutOfBoundsException("fromIndex: " + fromIndex +
  352. " > toIndex: " + toIndex);
  353. int startUnitIndex = unitIndex(fromIndex);
  354. if (startUnitIndex >= unitsInUse)
  355. return;
  356. int endUnitIndex = unitIndex(toIndex);
  357. long bitMask = 0;
  358. if (startUnitIndex == endUnitIndex) {
  359. // Case 1: One word
  360. bitMask = (1L << (toIndex & BIT_INDEX_MASK)) -
  361. (1L << (fromIndex & BIT_INDEX_MASK));
  362. bits[startUnitIndex] &= ~bitMask;
  363. if (bits[unitsInUse-1] == 0)
  364. recalculateUnitsInUse();
  365. return;
  366. }
  367. // Case 2: Multiple words
  368. // Handle first word
  369. bitMask = bitsLeftOf(fromIndex & BIT_INDEX_MASK);
  370. bits[startUnitIndex] &= ~bitMask;
  371. // Handle intermediate words, if any
  372. if (endUnitIndex - startUnitIndex > 1) {
  373. for(int i=startUnitIndex+1; i<endUnitIndex; i++) {
  374. if (i < unitsInUse)
  375. bits[i] = 0;
  376. }
  377. }
  378. // Handle last word
  379. if (endUnitIndex < unitsInUse) {
  380. bitMask = bitsRightOf(toIndex & BIT_INDEX_MASK);
  381. bits[endUnitIndex] &= ~bitMask;
  382. }
  383. if (bits[unitsInUse-1] == 0)
  384. recalculateUnitsInUse();
  385. }
  386. /**
  387. * Sets all of the bits in this BitSet to <code>false</code>.
  388. *
  389. * @since 1.4
  390. */
  391. public void clear() {
  392. while (unitsInUse > 0)
  393. bits[--unitsInUse] = 0;
  394. }
  395. /**
  396. * Returns the value of the bit with the specified index. The value
  397. * is <code>true</code> if the bit with the index <code>bitIndex</code>
  398. * is currently set in this <code>BitSet</code> otherwise, the result
  399. * is <code>false</code>.
  400. *
  401. * @param bitIndex the bit index.
  402. * @return the value of the bit with the specified index.
  403. * @exception IndexOutOfBoundsException if the specified index is negative.
  404. */
  405. public boolean get(int bitIndex) {
  406. if (bitIndex < 0)
  407. throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
  408. boolean result = false;
  409. int unitIndex = unitIndex(bitIndex);
  410. if (unitIndex < unitsInUse)
  411. result = ((bits[unitIndex] & bit(bitIndex)) != 0);
  412. return result;
  413. }
  414. /**
  415. * Returns a new <tt>BitSet</tt> composed of bits from this <tt>BitSet</tt>
  416. * from <tt>fromIndex</tt>(inclusive) to <tt>toIndex</tt>(exclusive).
  417. *
  418. * @param fromIndex index of the first bit to include.
  419. * @param toIndex index after the last bit to include.
  420. * @return a new <tt>BitSet</tt> from a range of this <tt>BitSet</tt>.
  421. * @exception IndexOutOfBoundsException if <tt>fromIndex</tt> is negative,
  422. * or <tt>toIndex</tt> is negative, or <tt>fromIndex</tt> is
  423. * larger than <tt>toIndex</tt>.
  424. * @since 1.4
  425. */
  426. public BitSet get(int fromIndex, int toIndex) {
  427. if (fromIndex < 0)
  428. throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
  429. if (toIndex < 0)
  430. throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex);
  431. if (fromIndex > toIndex)
  432. throw new IndexOutOfBoundsException("fromIndex: " + fromIndex +
  433. " > toIndex: " + toIndex);
  434. // If no set bits in range return empty bitset
  435. if (length() <= fromIndex || fromIndex == toIndex)
  436. return new BitSet(0);
  437. // An optimization
  438. if (length() < toIndex)
  439. toIndex = length();
  440. BitSet result = new BitSet(toIndex - fromIndex);
  441. int startBitIndex = fromIndex & BIT_INDEX_MASK;
  442. int endBitIndex = toIndex & BIT_INDEX_MASK;
  443. int targetWords = (toIndex - fromIndex + 63)/64;
  444. int sourceWords = unitIndex(toIndex) - unitIndex(fromIndex) + 1;
  445. int inverseIndex = 64 - startBitIndex;
  446. int targetIndex = 0;
  447. int sourceIndex = unitIndex(fromIndex);
  448. // Process all words but the last word
  449. while (targetIndex < targetWords - 1)
  450. result.bits[targetIndex++] =
  451. (bits[sourceIndex++] >>> startBitIndex) |
  452. ((inverseIndex==64) ? 0 : bits[sourceIndex] << inverseIndex);
  453. // Process the last word
  454. result.bits[targetIndex] = (sourceWords == targetWords ?
  455. (bits[sourceIndex] & bitsRightOf(endBitIndex)) >>> startBitIndex :
  456. (bits[sourceIndex++] >>> startBitIndex) | ((inverseIndex==64) ? 0 :
  457. (getBits(sourceIndex) & bitsRightOf(endBitIndex)) << inverseIndex));
  458. // Set unitsInUse correctly
  459. result.unitsInUse = targetWords;
  460. result.recalculateUnitsInUse();
  461. return result;
  462. }
  463. /**
  464. * Returns the unit of this bitset at index j as if this bitset had an
  465. * infinite amount of storage.
  466. */
  467. private long getBits(int j) {
  468. return (j < unitsInUse) ? bits[j] : 0;
  469. }
  470. /**
  471. * Returns the index of the first bit that is set to <code>true</code>
  472. * that occurs on or after the specified starting index. If no such
  473. * bit exists then -1 is returned.
  474. *
  475. * To iterate over the <code>true</code> bits in a <code>BitSet</code>,
  476. * use the following loop:
  477. *
  478. * for(int i=bs.nextSetBit(0); i>=0; i=bs.nextSetBit(i+1)) {
  479. * // operate on index i here
  480. * }
  481. *
  482. * @param fromIndex the index to start checking from (inclusive).
  483. * @return the index of the next set bit.
  484. * @throws IndexOutOfBoundsException if the specified index is negative.
  485. * @since 1.4
  486. */
  487. public int nextSetBit(int fromIndex) {
  488. if (fromIndex < 0)
  489. throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
  490. int u = unitIndex(fromIndex);
  491. if (u >= unitsInUse)
  492. return -1;
  493. int testIndex = (fromIndex & BIT_INDEX_MASK);
  494. long unit = bits[u] >> testIndex;
  495. if (unit == 0)
  496. testIndex = 0;
  497. while((unit==0) && (u < unitsInUse-1))
  498. unit = bits[++u];
  499. if (unit == 0)
  500. return -1;
  501. testIndex += trailingZeroCnt(unit);
  502. return ((u * BITS_PER_UNIT) + testIndex);
  503. }
  504. private static int trailingZeroCnt(long val) {
  505. // Loop unrolled for performance
  506. int byteVal = (int)val & 0xff;
  507. if (byteVal != 0)
  508. return trailingZeroTable[byteVal];
  509. byteVal = (int)(val >>> 8) & 0xff;
  510. if (byteVal != 0)
  511. return trailingZeroTable[byteVal] + 8;
  512. byteVal = (int)(val >>> 16) & 0xff;
  513. if (byteVal != 0)
  514. return trailingZeroTable[byteVal] + 16;
  515. byteVal = (int)(val >>> 24) & 0xff;
  516. if (byteVal != 0)
  517. return trailingZeroTable[byteVal] + 24;
  518. byteVal = (int)(val >>> 32) & 0xff;
  519. if (byteVal != 0)
  520. return trailingZeroTable[byteVal] + 32;
  521. byteVal = (int)(val >>> 40) & 0xff;
  522. if (byteVal != 0)
  523. return trailingZeroTable[byteVal] + 40;
  524. byteVal = (int)(val >>> 48) & 0xff;
  525. if (byteVal != 0)
  526. return trailingZeroTable[byteVal] + 48;
  527. byteVal = (int)(val >>> 56) & 0xff;
  528. return trailingZeroTable[byteVal] + 56;
  529. }
  530. /*
  531. * trailingZeroTable[i] is the number of trailing zero bits in the binary
  532. * representaion of i.
  533. */
  534. private final static byte trailingZeroTable[] = {
  535. -25, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  536. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  537. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  538. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  539. 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  540. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  541. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  542. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  543. 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  544. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  545. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  546. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  547. 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  548. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  549. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  550. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
  551. /**
  552. * Returns the index of the first bit that is set to <code>false</code>
  553. * that occurs on or after the specified starting index.
  554. *
  555. * @param fromIndex the index to start checking from (inclusive).
  556. * @return the index of the next clear bit.
  557. * @throws IndexOutOfBoundsException if the specified index is negative.
  558. * @since 1.4
  559. */
  560. public int nextClearBit(int fromIndex) {
  561. if (fromIndex < 0)
  562. throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
  563. int u = unitIndex(fromIndex);
  564. if (u >= unitsInUse)
  565. return fromIndex;
  566. int testIndex = (fromIndex & BIT_INDEX_MASK);
  567. long unit = bits[u] >> testIndex;
  568. if (unit == (WORD_MASK >> testIndex))
  569. testIndex = 0;
  570. while((unit==WORD_MASK) && (u < unitsInUse-1))
  571. unit = bits[++u];
  572. if (unit == WORD_MASK)
  573. return length();
  574. if (unit == 0)
  575. return u * BITS_PER_UNIT + testIndex;
  576. testIndex += trailingZeroCnt(~unit);
  577. return ((u * BITS_PER_UNIT) + testIndex);
  578. }
  579. /**
  580. * Returns the "logical size" of this <code>BitSet</code>: the index of
  581. * the highest set bit in the <code>BitSet</code> plus one. Returns zero
  582. * if the <code>BitSet</code> contains no set bits.
  583. *
  584. * @return the logical size of this <code>BitSet</code>.
  585. * @since 1.2
  586. */
  587. public int length() {
  588. if (unitsInUse == 0)
  589. return 0;
  590. long highestUnit = bits[unitsInUse - 1];
  591. int highPart = (int)(highestUnit >>> 32);
  592. return 64 * (unitsInUse - 1) +
  593. (highPart == 0 ? bitLen((int)highestUnit)
  594. : 32 + bitLen((int)highPart));
  595. }
  596. /**
  597. * bitLen(val) is the number of bits in val.
  598. */
  599. private static int bitLen(int w) {
  600. // Binary search - decision tree (5 tests, rarely 6)
  601. return
  602. (w < 1<<15 ?
  603. (w < 1<<7 ?
  604. (w < 1<<3 ?
  605. (w < 1<<1 ? (w < 1<<0 ? (w<0 ? 32 : 0) : 1) : (w < 1<<2 ? 2 : 3)) :
  606. (w < 1<<5 ? (w < 1<<4 ? 4 : 5) : (w < 1<<6 ? 6 : 7))) :
  607. (w < 1<<11 ?
  608. (w < 1<<9 ? (w < 1<<8 ? 8 : 9) : (w < 1<<10 ? 10 : 11)) :
  609. (w < 1<<13 ? (w < 1<<12 ? 12 : 13) : (w < 1<<14 ? 14 : 15)))) :
  610. (w < 1<<23 ?
  611. (w < 1<<19 ?
  612. (w < 1<<17 ? (w < 1<<16 ? 16 : 17) : (w < 1<<18 ? 18 : 19)) :
  613. (w < 1<<21 ? (w < 1<<20 ? 20 : 21) : (w < 1<<22 ? 22 : 23))) :
  614. (w < 1<<27 ?
  615. (w < 1<<25 ? (w < 1<<24 ? 24 : 25) : (w < 1<<26 ? 26 : 27)) :
  616. (w < 1<<29 ? (w < 1<<28 ? 28 : 29) : (w < 1<<30 ? 30 : 31)))));
  617. }
  618. /**
  619. * Returns true if this <code>BitSet</code> contains no bits that are set
  620. * to <code>true</code>.
  621. *
  622. * @return boolean indicating whether this <code>BitSet</code> is empty.
  623. * @since 1.4
  624. */
  625. public boolean isEmpty() {
  626. return (unitsInUse == 0);
  627. }
  628. /**
  629. * Returns true if the specified <code>BitSet</code> has any bits set to
  630. * <code>true</code> that are also set to <code>true</code> in this
  631. * <code>BitSet</code>.
  632. *
  633. * @param set <code>BitSet</code> to intersect with
  634. * @return boolean indicating whether this <code>BitSet</code> intersects
  635. * the specified <code>BitSet</code>.
  636. * @since 1.4
  637. */
  638. public boolean intersects(BitSet set) {
  639. for(int i = Math.min(unitsInUse, set.unitsInUse)-1; i>=0; i--)
  640. if ((bits[i] & set.bits[i]) != 0)
  641. return true;
  642. return false;
  643. }
  644. /**
  645. * Returns the number of bits set to <tt>true</tt> in this
  646. * <code>BitSet</code>.
  647. *
  648. * @return the number of bits set to <tt>true</tt> in this
  649. * <code>BitSet</code>.
  650. * @since 1.4
  651. */
  652. public int cardinality() {
  653. int sum = 0;
  654. for (int i=0; i<unitsInUse; i++)
  655. sum += bitCount(bits[i]);
  656. return sum;
  657. }
  658. /**
  659. * Returns the number of bits set in val.
  660. * For a derivation of this algorithm, see
  661. * "Algorithms and data structures with applications to
  662. * graphics and geometry", by Jurg Nievergelt and Klaus Hinrichs,
  663. * Prentice Hall, 1993.
  664. */
  665. private static int bitCount(long val) {
  666. val -= (val & 0xaaaaaaaaaaaaaaaaL) >>> 1;
  667. val = (val & 0x3333333333333333L) + ((val >>> 2) & 0x3333333333333333L);
  668. val = (val + (val >>> 4)) & 0x0f0f0f0f0f0f0f0fL;
  669. val += val >>> 8;
  670. val += val >>> 16;
  671. return ((int)(val) + (int)(val >>> 32)) & 0xff;
  672. }
  673. /**
  674. * Performs a logical <b>AND</b> of this target bit set with the
  675. * argument bit set. This bit set is modified so that each bit in it
  676. * has the value <code>true</code> if and only if it both initially
  677. * had the value <code>true</code> and the corresponding bit in the
  678. * bit set argument also had the value <code>true</code>.
  679. *
  680. * @param set a bit set.
  681. */
  682. public void and(BitSet set) {
  683. if (this == set)
  684. return;
  685. // Perform logical AND on bits in common
  686. int oldUnitsInUse = unitsInUse;
  687. unitsInUse = Math.min(unitsInUse, set.unitsInUse);
  688. int i;
  689. for(i=0; i<unitsInUse; i++)
  690. bits[i] &= set.bits[i];
  691. // Clear out units no longer used
  692. for( ; i < oldUnitsInUse; i++)
  693. bits[i] = 0;
  694. // Recalculate units in use if necessary
  695. if (unitsInUse > 0 && bits[unitsInUse - 1] == 0)
  696. recalculateUnitsInUse();
  697. }
  698. /**
  699. * Performs a logical <b>OR</b> of this bit set with the bit set
  700. * argument. This bit set is modified so that a bit in it has the
  701. * value <code>true</code> if and only if it either already had the
  702. * value <code>true</code> or the corresponding bit in the bit set
  703. * argument has the value <code>true</code>.
  704. *
  705. * @param set a bit set.
  706. */
  707. public void or(BitSet set) {
  708. if (this == set)
  709. return;
  710. ensureCapacity(set.unitsInUse);
  711. // Perform logical OR on bits in common
  712. int unitsInCommon = Math.min(unitsInUse, set.unitsInUse);
  713. int i;
  714. for(i=0; i<unitsInCommon; i++)
  715. bits[i] |= set.bits[i];
  716. // Copy any remaining bits
  717. for(; i<set.unitsInUse; i++)
  718. bits[i] = set.bits[i];
  719. if (unitsInUse < set.unitsInUse)
  720. unitsInUse = set.unitsInUse;
  721. }
  722. /**
  723. * Performs a logical <b>XOR</b> of this bit set with the bit set
  724. * argument. This bit set is modified so that a bit in it has the
  725. * value <code>true</code> if and only if one of the following
  726. * statements holds:
  727. * <ul>
  728. * <li>The bit initially has the value <code>true</code>, and the
  729. * corresponding bit in the argument has the value <code>false</code>.
  730. * <li>The bit initially has the value <code>false</code>, and the
  731. * corresponding bit in the argument has the value <code>true</code>.
  732. * </ul>
  733. *
  734. * @param set a bit set.
  735. */
  736. public void xor(BitSet set) {
  737. int unitsInCommon;
  738. if (unitsInUse >= set.unitsInUse) {
  739. unitsInCommon = set.unitsInUse;
  740. } else {
  741. unitsInCommon = unitsInUse;
  742. int newUnitsInUse = set.unitsInUse;
  743. ensureCapacity(newUnitsInUse);
  744. unitsInUse = newUnitsInUse;
  745. }
  746. // Perform logical XOR on bits in common
  747. int i;
  748. for (i=0; i<unitsInCommon; i++)
  749. bits[i] ^= set.bits[i];
  750. // Copy any remaining bits
  751. for ( ; i<set.unitsInUse; i++)
  752. bits[i] = set.bits[i];
  753. recalculateUnitsInUse();
  754. }
  755. /**
  756. * Clears all of the bits in this <code>BitSet</code> whose corresponding
  757. * bit is set in the specified <code>BitSet</code>.
  758. *
  759. * @param set the <code>BitSet</code> with which to mask this
  760. * <code>BitSet</code>.
  761. * @since JDK1.2
  762. */
  763. public void andNot(BitSet set) {
  764. int unitsInCommon = Math.min(unitsInUse, set.unitsInUse);
  765. // Perform logical (a & !b) on bits in common
  766. for (int i=0; i<unitsInCommon; i++) {
  767. bits[i] &= ~set.bits[i];
  768. }
  769. recalculateUnitsInUse();
  770. }
  771. /**
  772. * Returns a hash code value for this bit set. The has code
  773. * depends only on which bits have been set within this
  774. * <code>BitSet</code>. The algorithm used to compute it may
  775. * be described as follows.<p>
  776. * Suppose the bits in the <code>BitSet</code> were to be stored
  777. * in an array of <code>long</code> integers called, say,
  778. * <code>bits</code>, in such a manner that bit <code>k</code> is
  779. * set in the <code>BitSet</code> (for nonnegative values of
  780. * <code>k</code>) if and only if the expression
  781. * <pre>((k>>6) < bits.length) && ((bits[k>>6] & (1L << (bit & 0x3F))) != 0)</pre>
  782. * is true. Then the following definition of the <code>hashCode</code>
  783. * method would be a correct implementation of the actual algorithm:
  784. * <pre>
  785. * public int hashCode() {
  786. * long h = 1234;
  787. * for (int i = bits.length; --i >= 0; ) {
  788. * h ^= bits[i] * (i + 1);
  789. * }
  790. * return (int)((h >> 32) ^ h);
  791. * }</pre>
  792. * Note that the hash code values change if the set of bits is altered.
  793. * <p>Overrides the <code>hashCode</code> method of <code>Object</code>.
  794. *
  795. * @return a hash code value for this bit set.
  796. */
  797. public int hashCode() {
  798. long h = 1234;
  799. for (int i = bits.length; --i >= 0; )
  800. h ^= bits[i] * (i + 1);
  801. return (int)((h >> 32) ^ h);
  802. }
  803. /**
  804. * Returns the number of bits of space actually in use by this
  805. * <code>BitSet</code> to represent bit values.
  806. * The maximum element in the set is the size - 1st element.
  807. *
  808. * @return the number of bits currently in this bit set.
  809. */
  810. public int size() {
  811. return bits.length << ADDRESS_BITS_PER_UNIT;
  812. }
  813. /**
  814. * Compares this object against the specified object.
  815. * The result is <code>true</code> if and only if the argument is
  816. * not <code>null</code> and is a <code>Bitset</code> object that has
  817. * exactly the same set of bits set to <code>true</code> as this bit
  818. * set. That is, for every nonnegative <code>int</code> index <code>k</code>,
  819. * <pre>((BitSet)obj).get(k) == this.get(k)</pre>
  820. * must be true. The current sizes of the two bit sets are not compared.
  821. * <p>Overrides the <code>equals</code> method of <code>Object</code>.
  822. *
  823. * @param obj the object to compare with.
  824. * @return <code>true</code> if the objects are the same;
  825. * <code>false</code> otherwise.
  826. * @see java.util.BitSet#size()
  827. */
  828. public boolean equals(Object obj) {
  829. if (!(obj instanceof BitSet))
  830. return false;
  831. if (this == obj)
  832. return true;
  833. BitSet set = (BitSet) obj;
  834. int minUnitsInUse = Math.min(unitsInUse, set.unitsInUse);
  835. // Check units in use by both BitSets
  836. for (int i = 0; i < minUnitsInUse; i++)
  837. if (bits[i] != set.bits[i])
  838. return false;
  839. // Check any units in use by only one BitSet (must be 0 in other)
  840. if (unitsInUse > minUnitsInUse) {
  841. for (int i = minUnitsInUse; i<unitsInUse; i++)
  842. if (bits[i] != 0)
  843. return false;
  844. } else {
  845. for (int i = minUnitsInUse; i<set.unitsInUse; i++)
  846. if (set.bits[i] != 0)
  847. return false;
  848. }
  849. return true;
  850. }
  851. /**
  852. * Cloning this <code>BitSet</code> produces a new <code>BitSet</code>
  853. * that is equal to it.
  854. * The clone of the bit set is another bit set that has exactly the
  855. * same bits set to <code>true</code> as this bit set and the same
  856. * current size.
  857. * <p>Overrides the <code>clone</code> method of <code>Object</code>.
  858. *
  859. * @return a clone of this bit set.
  860. * @see java.util.BitSet#size()
  861. */
  862. public Object clone() {
  863. BitSet result = null;
  864. try {
  865. result = (BitSet) super.clone();
  866. } catch (CloneNotSupportedException e) {
  867. throw new InternalError();
  868. }
  869. result.bits = new long[bits.length];
  870. System.arraycopy(bits, 0, result.bits, 0, unitsInUse);
  871. return result;
  872. }
  873. /**
  874. * This override of readObject makes sure unitsInUse is set properly
  875. * when deserializing a bitset
  876. *
  877. */
  878. private void readObject(java.io.ObjectInputStream in)
  879. throws IOException, ClassNotFoundException {
  880. in.defaultReadObject();
  881. // Assume maximum length then find real length
  882. // because recalculateUnitsInUse assumes maintenance
  883. // or reduction in logical size
  884. unitsInUse = bits.length;
  885. recalculateUnitsInUse();
  886. }
  887. /**
  888. * Returns a string representation of this bit set. For every index
  889. * for which this <code>BitSet</code> contains a bit in the set
  890. * state, the decimal representation of that index is included in
  891. * the result. Such indices are listed in order from lowest to
  892. * highest, separated by ", " (a comma and a space) and
  893. * surrounded by braces, resulting in the usual mathematical
  894. * notation for a set of integers.<p>
  895. * Overrides the <code>toString</code> method of <code>Object</code>.
  896. * <p>Example:
  897. * <pre>
  898. * BitSet drPepper = new BitSet();</pre>
  899. * Now <code>drPepper.toString()</code> returns "<code>{}</code>".<p>
  900. * <pre>
  901. * drPepper.set(2);</pre>
  902. * Now <code>drPepper.toString()</code> returns "<code>{2}</code>".<p>
  903. * <pre>
  904. * drPepper.set(4);
  905. * drPepper.set(10);</pre>
  906. * Now <code>drPepper.toString()</code> returns "<code>{2, 4, 10}</code>".
  907. *
  908. * @return a string representation of this bit set.
  909. */
  910. public String toString() {
  911. int numBits = unitsInUse << ADDRESS_BITS_PER_UNIT;
  912. StringBuffer buffer = new StringBuffer(8*numBits + 2);
  913. String separator = "";
  914. buffer.append('{');
  915. for (int i = 0 ; i < numBits; i++) {
  916. if (get(i)) {
  917. buffer.append(separator);
  918. separator = ", ";
  919. buffer.append(i);
  920. }
  921. }
  922. buffer.append('}');
  923. return buffer.toString();
  924. }
  925. }