[英]Is it possible to set bits while creating a BitSet?
I need to create a few BitSets in a loop, something like:我需要在循环中创建一些 BitSet,例如:
ArrayList<BitSet> bitSetList = new ArrayList<BitSet>();
for (int x : array) {
bitSetList.add(new BitSet() //and set bits in specific places)
}
(To create a BitSet & set specific bits,) You can use one of: (要创建 BitSet 并设置特定位,)您可以使用以下方法之一:
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 API-DOC: https : //docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/BitSet.html
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
有几个称为valueOf
静态重载方法,您可以使用它们创建一个BitSet
初始化并使用其中设置的位,例如byte
数组:
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%5B%5D)请参阅: https : //docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/BitSet.html#valueOf(byte%5B%5D)
Like any other object in Java, you can create a BitSet object and add it to a List in this manner.与 Java 中的任何其他对象一样,您可以创建一个 BitSet 对象并将其添加到列表中。 Before adding it to the List, I would create the BitSet object and add data to the object.
在将它添加到列表之前,我将创建 BitSet 对象并向该对象添加数据。
You can you stream to create a BitSet
of each ints like that:您可以流式传输以创建每个整数的
BitSet
,如下所示:
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.如果您不喜欢
.map(BitSet::new)
的编写方式,可以将其替换为.map(i -> new BitSet(i))
。
You should use BitSet.valueOf()
.您应该使用
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.