[英]Whats the list.size() equivalent of the BitSet?
My question would be better understood by the code below. 我的问题将通过下面的代码更好地理解。 I need to know how last bit set by me. 我需要知道我最后的设定。 How do I find it in bitset ? 如何在位集中找到它?
public class FreeMain {
FreeMain ( ) { }
public static void takeBitSet(BitSet bitSet) {
// I intend to read 30 positions from bit set since the for loop looped from 0 to 29.
// Just like list.size() would have given me number of elements added to it
// whats the "list.size()" equivalent for bitset ?
}
public static void main(String[] args) throws IOException {
BitSet bs = new BitSet();
System.out.println(bs.length());
for (int i = 0; i < 30; i++) {
bs.set(i);
System.out.print(bs.get(i));
}
takeBitSet(bs);
}
}
There's cardinality()
, which returns the number of bits that are set. 有cardinality()
,它返回设置的位数。
There's also length()
, which returns 1 + the index of the highest bit set. 还有length()
,它返回1 +最高位集的索引。
And there's size()
, which returns the capacity, in bits, of the set. 还有size()
,以位为单位返回集合的容量。
Of those three length() - 1
is the closest thing to the "last bit set by you", but note that it is the index of the highest set bit, not the index of the most recently set bit (which is not possible using only BitSet
). 在这三个length() - 1
是最接近“您设置的最后一位”的东西,但是请注意,它是最高设置位的索引,而不是最近设置位的索引(使用仅BitSet
)。
You also mentioned "number of elements added to it", for which cardinality()
is the closest match (as long as you don't consider setting a bit to 0 to be semantically equivalent to "adding a 0 to the set"). 您还提到了“添加到其中的元素数”,其中cardinality()
是最接近的匹配项(只要您不考虑将bit设置为0在语义上等同于“向set中添加0”)。
I wasn't quite sure what the answer was (Jason C's is great). 我不太确定答案是什么(Jason C's很好)。 I threw together a tiny test to get a feel for it though (Java 7, 64-bit system): 我进行了一个小小的测试来了解它(Java 7,64位系统):
import java.util.BitSet;
public class BitSetTest {
public static void main(String[] args) {
BitSet bset = new BitSet();
for (int i = 0; i < 65; i++) {
bset.set(i);
}
bset.set(78);
System.out.println("Cardinality = " + bset.cardinality());
System.out.println("Size = " + bset.size());
System.out.println("Length = " + bset.length());
}
}
Output: 输出:
Cardinality = 66
Size = 128
Length = 79
In this setup, you can take size to mean the amount of bits the set has available. 在此设置中,您可以采用大小来表示集合可用的位数。 (which increases when you exceed the initial size). (当您超过初始大小时会增加)。 Cardinality is the actual amount of elements that have been set so far. 基数是到目前为止已设置的元素的实际数量。 Length is the highest bit that was set, which you can see was 79, and the bits between may or may not have been set (depending on how the set was used prior). 长度是设置的最高位,您可以看到是79,并且之间的位可能已设置也可能未设置(取决于之前使用该设置的方式)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.