BitSetUtils { public static boolean[] toArray(BitSet bitset, int length) { if (length < 0) { throw new IllegalArgumentException("Size of array must not be negative but was + " + length); } boolean[] array = new boolean[length]; for (int i = 0; i < length; i++) { array[i] = bitset.get(i); } return array; } private  BitSetUtils(); static BitSet copy(BitSet b); static BitSet getRandomBits(int n, Random random); static String toString(BitSet bits, int n); static String toString(BitSet bits); static boolean innerProduct(BitSet a, BitSet b); static BitSet fromList(List<Boolean> list); static BitSet fromArray(boolean[] array); static boolean[] toArray(BitSet bitset, int length); static List<Boolean> toList(BitSet bitset, int n);  }
@Test public void testToArray() { int[] indices = new int[] { 0, 1, 4, 10, 6, 9, 11 }; BitSet bitSet = new BitSet(20); for (int i: indices) { bitSet.set(i); } boolean[] array = BitSetUtils.toArray(bitSet, bitSet.size()); Assert.assertEquals(bitSet.size(), array.length); for (int i = 0; i < bitSet.size(); i++) { Assert.assertEquals(bitSet.get(i), array[i]); } boolean[] shortArray = BitSetUtils.toArray(bitSet, 5); Assert.assertEquals(5, shortArray.length); for (int i = 0; i < 5; i++) { Assert.assertEquals(bitSet.get(i), shortArray[i]); } boolean[] longArray = BitSetUtils.toArray(bitSet, bitSet.size() + 10); Assert.assertEquals(bitSet.size() + 10, longArray.length); for (int i = 0; i < bitSet.size() + 10; i++) { Assert.assertEquals(bitSet.get(i), longArray[i]); } boolean exception = false; try { BitSetUtils.toArray(bitSet, -2); } catch (IllegalArgumentException e) { exception = true; } Assert.assertTrue(exception); }