import java.util.BitSet; public class FlagCollection { private BitSet flags; public FlagCollection(int numFlags) { flags = new BitSet(numFlags); } public int getNextAvailableFlag() { int nextFlag = flags.nextClearBit(0); if (nextFlag < flags.size()) { flags.set(nextFlag); return nextFlag; } return -1; // no available flags } // other methods... }
import java.util.BitSet; public class PrimeGenerator { public static void main(String[] args) { int numPrimes = 100; BitSet primeFlags = new BitSet(); int currentPrime = 2; while (numPrimes > 0) { System.out.print(currentPrime + " "); primeFlags.set(currentPrime); numPrimes--; // find next prime number currentPrime = primeFlags.nextClearBit(currentPrime + 1); while (!isPrime(currentPrime)) { currentPrime = primeFlags.nextClearBit(currentPrime + 1); } } } private static boolean isPrime(int n) { // code to check if n is prime } }This code generates a sequence of prime numbers using a Sieve of Eratosthenes algorithm. It creates a BitSet to keep track of which numbers have been checked for primality, and starts with the first prime number, 2. It prints each prime number found and sets its corresponding bit in the BitSet. The next prime number is found by searching for the next unset bit after the current prime number, skipping over any numbers that are not prime. Both of these examples use java.util.BitSet from the standard Java library.