1. /*
  2. * @(#)BitSet.java 1.46 00/02/02
  3. *
  4. * Copyright 1995-2000 Sun Microsystems, Inc. All Rights Reserved.
  5. *
  6. * This software is the proprietary information of Sun Microsystems, Inc.
  7. * Use is subject to license terms.
  8. *
  9. */
  10. package java.util;
  11. import java.io.*;
  12. /**
  13. * This class implements a vector of bits that grows as needed. Each
  14. * component of the bit set has a <code>boolean</code> value. The
  15. * bits of a <code>BitSet</code> are indexed by nonnegative integers.
  16. * Individual indexed bits can be examined, set, or cleared. One
  17. * <code>BitSet</code> may be used to modify the contents of another
  18. * <code>BitSet</code> through logical AND, logical inclusive OR, and
  19. * logical exclusive OR operations.
  20. * <p>
  21. * By default, all bits in the set initially have the value
  22. * <code>false</code>.
  23. * <p>
  24. * Every bit set has a current size, which is the number of bits
  25. * of space currently in use by the bit set. Note that the size is
  26. * related to the implementation of a bit set, so it may change with
  27. * implementation. The length of a bit set relates to logical length
  28. * of a bit set and is defined independently of implementation.
  29. *
  30. * @author Arthur van Hoff
  31. * @author Michael McCloskey
  32. * @version 1.46, 02/02/00
  33. * @since JDK1.0
  34. */
  35. public class BitSet implements Cloneable, java.io.Serializable {
  36. /*
  37. * BitSets are packed into arrays of "units." Currently a unit is a long,
  38. * which consists of 64 bits, requiring 6 address bits. The choice of unit
  39. * is determined purely by performance concerns.
  40. */
  41. private final static int ADDRESS_BITS_PER_UNIT = 6;
  42. private final static int BITS_PER_UNIT = 1 << ADDRESS_BITS_PER_UNIT;
  43. private final static int BIT_INDEX_MASK = BITS_PER_UNIT - 1;
  44. /**
  45. * The bits in this BitSet. The ith bit is stored in bits[i/64] at
  46. * bit position i % 64 (where bit position 0 refers to the least
  47. * significant bit and 63 refers to the most significant bit).
  48. * INVARIANT: The words in bits[] above unitInUse-1 are zero.
  49. *
  50. * @serial
  51. */
  52. private long bits[]; // this should be called unit[]
  53. /**
  54. * The number of units in the logical size of this BitSet.
  55. * INVARIANT: unitsInUse is nonnegative.
  56. * INVARIANT: bits[unitsInUse-1] is nonzero unless unitsInUse is zero.
  57. */
  58. private transient int unitsInUse = 0;
  59. /* use serialVersionUID from JDK 1.0.2 for interoperability */
  60. private static final long serialVersionUID = 7997698588986878753L;
  61. /**
  62. * Given a bit index return unit index containing it.
  63. */
  64. private static int unitIndex(int bitIndex) {
  65. return bitIndex >> ADDRESS_BITS_PER_UNIT;
  66. }
  67. /**
  68. * Given a bit index, return a unit that masks that bit in its unit.
  69. */
  70. private static long bit(int bitIndex) {
  71. return 1L << (bitIndex & BIT_INDEX_MASK);
  72. }
  73. /**
  74. * Set the field unitsInUse with the logical size in units of the bit
  75. * set. WARNING:This function assumes that the number of units actually
  76. * in use is less than or equal to the current value of unitsInUse!
  77. */
  78. private void recalculateUnitsInUse() {
  79. /* Traverse the bitset until a used unit is found */
  80. int i;
  81. for (i = unitsInUse-1; i >= 0; i--)
  82. if(bits[i] != 0)
  83. break; //this unit is in use!
  84. unitsInUse = i+1; //the new logical size
  85. }
  86. /**
  87. * Creates a new bit set. All bits are initially <code>false</code>.
  88. */
  89. public BitSet() {
  90. this(BITS_PER_UNIT);
  91. }
  92. /**
  93. * Creates a bit set whose initial size is large enough to explicitly
  94. * represent bits with indices in the range <code>0</code> through
  95. * <code>nbits-1</code>. All bits are initially <code>false</code>.
  96. *
  97. * @param nbits the initial size of the bit set.
  98. * @exception NegativeArraySizeException if the specified initial size
  99. * is negative.
  100. */
  101. public BitSet(int nbits) {
  102. /* nbits can't be negative; size 0 is OK */
  103. if (nbits < 0)
  104. throw new NegativeArraySizeException(Integer.toString(nbits));
  105. bits = new long[(unitIndex(nbits-1) + 1)];
  106. }
  107. /**
  108. * Ensures that the BitSet can hold enough units.
  109. * @param unitsRequired the minimum acceptable number of units.
  110. */
  111. private void ensureCapacity(int unitsRequired) {
  112. if (bits.length < unitsRequired) {
  113. /* Allocate larger of doubled size or required size */
  114. int request = Math.max(2 * bits.length, unitsRequired);
  115. long newBits[] = new long[request];
  116. System.arraycopy(bits, 0, newBits, 0, unitsInUse);
  117. bits = newBits;
  118. }
  119. }
  120. /**
  121. * Returns the "logical size" of this <code>BitSet</code>: the index of
  122. * the highest set bit in the <code>BitSet</code> plus one. Returns zero
  123. * if the <code>BitSet</code> contains no set bits.
  124. *
  125. * @return the logical size of this <code>BitSet</code>.
  126. * @since 1.2
  127. */
  128. public int length() {
  129. if (unitsInUse == 0)
  130. return 0;
  131. int highestBit = (unitsInUse - 1) * 64;
  132. long highestUnit = bits[unitsInUse - 1];
  133. do {
  134. highestUnit = highestUnit >>> 1;
  135. highestBit++;
  136. } while(highestUnit > 0);
  137. return highestBit;
  138. }
  139. /**
  140. * Sets the bit specified by the index to <code>true</code>.
  141. *
  142. * @param bitIndex a bit index.
  143. * @exception IndexOutOfBoundsException if the specified index is negative.
  144. * @since JDK1.0
  145. */
  146. public void set(int bitIndex) {
  147. if (bitIndex < 0)
  148. throw new IndexOutOfBoundsException(Integer.toString(bitIndex));
  149. int unitIndex = unitIndex(bitIndex);
  150. int unitsRequired = unitIndex+1;
  151. if (unitsInUse < unitsRequired) {
  152. ensureCapacity(unitsRequired);
  153. bits[unitIndex] |= bit(bitIndex);
  154. unitsInUse = unitsRequired;
  155. } else {
  156. bits[unitIndex] |= bit(bitIndex);
  157. }
  158. }
  159. /**
  160. * Sets the bit specified by the index to <code>false</code>.
  161. *
  162. * @param bitIndex the index of the bit to be cleared.
  163. * @exception IndexOutOfBoundsException if the specified index is negative.
  164. * @since JDK1.0
  165. */
  166. public void clear(int bitIndex) {
  167. if (bitIndex < 0)
  168. throw new IndexOutOfBoundsException(Integer.toString(bitIndex));
  169. int unitIndex = unitIndex(bitIndex);
  170. if (unitIndex >= unitsInUse)
  171. return;
  172. bits[unitIndex] &= ~bit(bitIndex);
  173. if (bits[unitsInUse-1] == 0)
  174. recalculateUnitsInUse();
  175. }
  176. /**
  177. * Clears all of the bits in this <code>BitSet</code> whose corresponding
  178. * bit is set in the specified <code>BitSet</code>.
  179. *
  180. * @param set the <code>BitSet</code> with which to mask this
  181. * <code>BitSet</code>.
  182. * @since 1.2
  183. */
  184. public void andNot(BitSet set) {
  185. int unitsInCommon = Math.min(unitsInUse, set.unitsInUse);
  186. // perform logical (a & !b) on bits in common
  187. for (int i=0; i<unitsInCommon; i++) {
  188. bits[i] &= ~set.bits[i];
  189. }
  190. recalculateUnitsInUse();
  191. }
  192. /**
  193. * Returns the value of the bit with the specified index. The value
  194. * is <code>true</code> if the bit with the index <code>bitIndex</code>
  195. * is currently set in this <code>BitSet</code> otherwise, the result
  196. * is <code>false</code>.
  197. *
  198. * @param bitIndex the bit index.
  199. * @return the value of the bit with the specified index.
  200. * @exception IndexOutOfBoundsException if the specified index is negative.
  201. */
  202. public boolean get(int bitIndex) {
  203. if (bitIndex < 0)
  204. throw new IndexOutOfBoundsException(Integer.toString(bitIndex));
  205. boolean result = false;
  206. int unitIndex = unitIndex(bitIndex);
  207. if (unitIndex < unitsInUse)
  208. result = ((bits[unitIndex] & bit(bitIndex)) != 0);
  209. return result;
  210. }
  211. /**
  212. * Performs a logical <b>AND</b> of this target bit set with the
  213. * argument bit set. This bit set is modified so that each bit in it
  214. * has the value <code>true</code> if and only if it both initially
  215. * had the value <code>true</code> and the corresponding bit in the
  216. * bit set argument also had the value <code>true</code>.
  217. *
  218. * @param set a bit set.
  219. */
  220. public void and(BitSet set) {
  221. if (this == set)
  222. return;
  223. // perform logical AND on bits in common
  224. int oldUnitsInUse = unitsInUse;
  225. unitsInUse = Math.min(unitsInUse, set.unitsInUse);
  226. int i;
  227. for(i=0; i<unitsInUse; i++)
  228. bits[i] &= set.bits[i];
  229. // clear out units no longer used
  230. for( ; i < oldUnitsInUse; i++)
  231. bits[i] = 0;
  232. // Recalculate units in use if necessary
  233. if (unitsInUse > 0 && bits[unitsInUse - 1] == 0)
  234. recalculateUnitsInUse();
  235. }
  236. /**
  237. * Performs a logical <b>OR</b> of this bit set with the bit set
  238. * argument. This bit set is modified so that a bit in it has the
  239. * value <code>true</code> if and only if it either already had the
  240. * value <code>true</code> or the corresponding bit in the bit set
  241. * argument has the value <code>true</code>.
  242. *
  243. * @param set a bit set.
  244. */
  245. public void or(BitSet set) {
  246. if (this == set)
  247. return;
  248. ensureCapacity(set.unitsInUse);
  249. // perform logical OR on bits in common
  250. int unitsInCommon = Math.min(unitsInUse, set.unitsInUse);
  251. int i;
  252. for(i=0; i<unitsInCommon; i++)
  253. bits[i] |= set.bits[i];
  254. // copy any remaining bits
  255. for(; i<set.unitsInUse; i++)
  256. bits[i] = set.bits[i];
  257. if (unitsInUse < set.unitsInUse)
  258. unitsInUse = set.unitsInUse;
  259. }
  260. /**
  261. * Performs a logical <b>XOR</b> of this bit set with the bit set
  262. * argument. This bit set is modified so that a bit in it has the
  263. * value <code>true</code> if and only if one of the following
  264. * statements holds:
  265. * <ul>
  266. * <li>The bit initially has the value <code>true</code>, and the
  267. * corresponding bit in the argument has the value <code>false</code>.
  268. * <li>The bit initially has the value <code>false</code>, and the
  269. * corresponding bit in the argument has the value <code>true</code>.
  270. * </ul>
  271. *
  272. * @param set a bit set.
  273. */
  274. public void xor(BitSet set) {
  275. int unitsInCommon;
  276. if (unitsInUse >= set.unitsInUse) {
  277. unitsInCommon = set.unitsInUse;
  278. } else {
  279. unitsInCommon = unitsInUse;
  280. int newUnitsInUse = set.unitsInUse;
  281. ensureCapacity(newUnitsInUse);
  282. unitsInUse = newUnitsInUse;
  283. }
  284. // perform logical XOR on bits in common
  285. int i;
  286. for (i=0; i<unitsInCommon; i++)
  287. bits[i] ^= set.bits[i];
  288. // copy any remaining bits
  289. for ( ; i<set.unitsInUse; i++)
  290. bits[i] = set.bits[i];
  291. recalculateUnitsInUse();
  292. }
  293. /**
  294. * Returns a hash code value for this bit set. The has code
  295. * depends only on which bits have been set within this
  296. * <code>BitSet</code>. The algorithm used to compute it may
  297. * be described as follows.<p>
  298. * Suppose the bits in the <code>BitSet</code> were to be stored
  299. * in an array of <code>long</code> integers called, say,
  300. * <code>bits</code>, in such a manner that bit <code>k</code> is
  301. * set in the <code>BitSet</code> (for nonnegative values of
  302. * <code>k</code>) if and only if the expression
  303. * <pre>((k>>6) < bits.length) && ((bits[k>>6] & (1L << (bit & 0x3F))) != 0)</pre>
  304. * is true. Then the following definition of the <code>hashCode</code>
  305. * method would be a correct implementation of the actual algorithm:
  306. * <pre>
  307. * public synchronized int hashCode() {
  308. * long h = 1234;
  309. * for (int i = bits.length; --i >= 0; ) {
  310. * h ^= bits[i] * (i + 1);
  311. * }
  312. * return (int)((h >> 32) ^ h);
  313. * }</pre>
  314. * Note that the hash code values change if the set of bits is altered.
  315. * <p>Overrides the <code>hashCode</code> method of <code>Object</code>.
  316. *
  317. * @return a hash code value for this bit set.
  318. */
  319. public int hashCode() {
  320. long h = 1234;
  321. for (int i = bits.length; --i >= 0; )
  322. h ^= bits[i] * (i + 1);
  323. return (int)((h >> 32) ^ h);
  324. }
  325. /**
  326. * Returns the number of bits of space actually in use by this
  327. * <code>BitSet</code> to represent bit values.
  328. * The maximum element in the set is the size - 1st element.
  329. *
  330. * @return the number of bits currently in this bit set.
  331. */
  332. public int size() {
  333. return bits.length << ADDRESS_BITS_PER_UNIT;
  334. }
  335. /**
  336. * Compares this object against the specified object.
  337. * The result is <code>true</code> if and only if the argument is
  338. * not <code>null</code> and is a <code>Bitset</code> object that has
  339. * exactly the same set of bits set to <code>true</code> as this bit
  340. * set. That is, for every nonnegative <code>int</code> index <code>k</code>,
  341. * <pre>((BitSet)obj).get(k) == this.get(k)</pre>
  342. * must be true. The current sizes of the two bit sets are not compared.
  343. * <p>Overrides the <code>equals</code> method of <code>Object</code>.
  344. *
  345. * @param obj the object to compare with.
  346. * @return <code>true</code> if the objects are the same;
  347. * <code>false</code> otherwise.
  348. * @see java.util.BitSet#size()
  349. */
  350. public boolean equals(Object obj) {
  351. if (!(obj instanceof BitSet))
  352. return false;
  353. if (this == obj)
  354. return true;
  355. BitSet set = (BitSet) obj;
  356. int minUnitsInUse = Math.min(unitsInUse, set.unitsInUse);
  357. // Check units in use by both BitSets
  358. for (int i = 0; i < minUnitsInUse; i++)
  359. if (bits[i] != set.bits[i])
  360. return false;
  361. // Check any units in use by only one BitSet (must be 0 in other)
  362. if (unitsInUse > minUnitsInUse) {
  363. for (int i = minUnitsInUse; i<unitsInUse; i++)
  364. if (bits[i] != 0)
  365. return false;
  366. } else {
  367. for (int i = minUnitsInUse; i<set.unitsInUse; i++)
  368. if (set.bits[i] != 0)
  369. return false;
  370. }
  371. return true;
  372. }
  373. /**
  374. * Cloning this <code>BitSet</code> produces a new <code>BitSet</code>
  375. * that is equal to it.
  376. * The clone of the bit set is another bit set that has exactly the
  377. * same bits set to <code>true</code> as this bit set and the same
  378. * current size.
  379. * <p>Overrides the <code>clone</code> method of <code>Object</code>.
  380. *
  381. * @return a clone of this bit set.
  382. * @see java.util.BitSet#size()
  383. */
  384. public Object clone() {
  385. BitSet result = null;
  386. try {
  387. result = (BitSet) super.clone();
  388. } catch (CloneNotSupportedException e) {
  389. throw new InternalError();
  390. }
  391. result.bits = new long[bits.length];
  392. System.arraycopy(bits, 0, result.bits, 0, unitsInUse);
  393. return result;
  394. }
  395. /**
  396. * This override of readObject makes sure unitsInUse is set properly
  397. * when deserializing a bitset
  398. *
  399. */
  400. private void readObject(java.io.ObjectInputStream in)
  401. throws IOException, ClassNotFoundException {
  402. in.defaultReadObject();
  403. //assume maximum length then find real length
  404. //because recalculateUnitsInUse assumes maintenance
  405. //or reduction in logical size
  406. unitsInUse = bits.length;
  407. recalculateUnitsInUse();
  408. }
  409. /**
  410. * Returns a string representation of this bit set. For every index
  411. * for which this <code>BitSet</code> contains a bit in the set
  412. * state, the decimal representation of that index is included in
  413. * the result. Such indeces aer listed in order from lowest to
  414. * highest, separated by ",$nbsp;" (a comma and a space) and
  415. * surrounded by braces, resulting in the usual mathematical
  416. * notation for a set of integers.<p>
  417. * Overrides the <code>toString</code> method of <code>Object</code>.
  418. * <p>Example:
  419. * <pre>
  420. * BitSet drPepper = new BitSet();</pre>
  421. * Now <code>drPepper.toString()</code> returns "<code>{}</code>".<p>
  422. * <pre>
  423. * drPepper.set(2);</pre>
  424. * Now <code>drPepper.toString()</code> returns "<code>{2}</code>".<p>
  425. * <pre>
  426. * drPepper.set(4);
  427. * drPepper.set(10);</pre>
  428. * Now <code>drPepper.toString()</code> returns "<code>{2, 4, 10}</code>".
  429. *
  430. * @return a string representation of this bit set.
  431. */
  432. public String toString() {
  433. int numBits = unitsInUse << ADDRESS_BITS_PER_UNIT;
  434. StringBuffer buffer = new StringBuffer(8*numBits + 2);
  435. String separator = "";
  436. buffer.append('{');
  437. for (int i = 0 ; i < numBits; i++) {
  438. if (get(i)) {
  439. buffer.append(separator);
  440. separator = ", ";
  441. buffer.append(i);
  442. }
  443. }
  444. buffer.append('}');
  445. return buffer.toString();
  446. }
  447. }