I need to create a few BitSets in a loop, something like:
ArrayList<BitSet> bitSetList = new ArrayList<BitSet>();
for (int x : array) {
bitSetList.add(new BitSet() //and set bits in specific places)
}
CodePudding user response:
(To create a BitSet & set specific bits,) You can use one of:
-
static BitSet valueOf(byte[] bytes) /** Returns a new bit set containing all the bits in the given byte array.**/
-
static BitSet valueOf(long[] longs) /** Returns a new bit set containing all the bits in the given long array.*//
-
static BitSet valueOf(ByteBuffer bb) /** Returns a new bit set containing all the bits in the given byte buffer between its position and limit.**/
-
static BitSet valueOf(LongBuffer lb) /**Returns a new bit set containing all the bits in the given long buffer between its position and limit.**/
API-DOC: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/BitSet.html
CodePudding user response:
BitSet
has several static overloaded methods called valueOf
with which you can create a BitSet
initalized with the bits set in them, for example a byte
array:
BitSet example = BitSet.valueOf(new byte[] { 0b101 });
System.out.println(example.get(0)); // Prints true
System.out.println(example.get(1)); // Prints false
System.out.println(example.get(2)); // Prints true
See: https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/BitSet.html#valueOf(byte[])
CodePudding user response:
Like any other object in Java, you can create a BitSet object and add it to a List in this manner. Before adding it to the List, I would create the BitSet object and add data to the object.
CodePudding user response:
You can you stream to create a BitSet
of each ints like that:
List<Integer> ints = Arrays.asList(1, 8, 15);
List<BitSet> list = ints.stream().map(BitSet::new).collect(Collectors.toList());
System.out.println(list);
The .map(BitSet::new)
can be replaced by .map(i -> new BitSet(i))
if you don't like how it's wrote.
CodePudding user response:
You should use BitSet.valueOf()
. Just to merry this post. Here is a mess hack.
ArrayList<BitSet> bitSetList = new ArrayList<BitSet>();
bitSetList.add(new BitSet() {
public BitSet setMultiple(final int[] bitArray) {
for(int i=0; i < bitArray.length; i)
set(bitArray[i]);
return this;
};
}.setMultiple(array));