java.util.BitSet Class

This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations. By default, all bits in the set initially have the value false.

Every bit set has a current size, which is the number of bits of space currently in use by the bit set. Note that the size is related to the implementation of a bit set, so it may change with implementation. The length of a bit set relates to logical length of a bit set and is defined independently of implementation.

Unless otherwise noted, passing a null parameter to any of the methods in a BitSet will result in a NullPointerException. A BitSet is not safe for multithreaded use without external synchronization.

java.util.BitSet Class Example
/* Following example computes all primes up to 1000000. */
/* Save with file name BitSetExample.java */

import java.util.BitSet;

public class BitSetExample
{
	public static final boolean PRINT = false;
	public static void main(String args[])
	{
		int n = 1000000;
		long start = System.currentTimeMillis();
		//java.util.BitSet DECLARATION
		BitSet bs;

		//java.util.BitSet OBJECT CREATION
		bs = new BitSet(n);

		int count = 0;
		int i;
		for (i = 2; i<=n; i++)
		{
			bs.set(i);
		}

		i = 2;
		while(i * i <=n)
		{
			if(bs.get(i))
			{
				if(PRINT)
					System.out.println(i);
				count++;
				int k = 2 * i;
				while(k<=n)
				{
					bs.clear(k);
					k += i;
				}
			}
			i++;
		}
		while(i<=n)
		{
			if(bs.get(i))
			{
				if(PRINT)
					System.out.println(i);
				count++;
			}
			i++;
		}
		long end = System.currentTimeMillis();
		System.out.println(count + " Primes");
		System.out.println((end - start) + " Milliseconds");
	}
}