简体   繁体   English

检查BitSet中的所有位是否都设置为true

[英]Check if all bits in BitSet are set to true

I'm using a BitSet in my application and would like to check with a method if all used bits in the BitSet are set to true . 我在我的应用程序中使用BitSet ,并希望检查一个方法,如果BitSet中的所有使用位都设置为true Now, I know of the method isEmpty() that checks if all bits are set to false , however I can't seem to find the positive case. 现在,我知道方法isEmpty()检查是否所有位都设置为false ,但我似乎无法找到正面情况。 I'm aware I could do something like someBitSet.cardinality() == someBitSet.size() , but this seems clumsy. 我知道我可以做像someBitSet.cardinality() == someBitSet.size()这样的事情,但这看起来很笨拙。 Am I missing something or is there an explicit reason why such a method is not implemented but the opposite case is? 我错过了什么,或者是否有明确的理由说明为什么没有实施这样的方法,但情况恰恰相反?

There's no thing like "all bits in BitSet ", because at any time you can set the bit which is greater than the maximal bit set so far. 没有像“ BitSet所有位”那样的东西,因为在任何时候你都可以设置比目前为止设置的最大位更大的位。 Suppose that you want to keep in BitSet up to 10 values. 假设您希望在BitSet保留最多10个值。 So you set 10 bits and want to check whether all of them are true. 所以你设置10位,并想检查是否所有这些都是真的。 However BitSet does not know that you have only 10 bits. 但是BitSet不知道你只有10位。 What if you have more? 怎么样你有更多? Next time you can call bitSet.set(10000) and it will work ( BitSet will resize automatically). 下次你可以调用bitSet.set(10000)它会工作( BitSet会自动调整大小)。

Note that bitSet.size() is not very helpful in general case: it's about consumed memory. 请注意, bitSet.size()在一般情况下不是很有用:它是关于消耗的内存。 Current implementation is always a multiple of 64, so if you have only 10 different states, someBitSet.cardinality() == someBitSet.size() will always return false. 当前实现始终是64的倍数,因此如果您只有10个不同的状态, someBitSet.cardinality() == someBitSet.size()将始终返回false。 Even if you created the BitSet with new BitSet(10) . 即使您使用new BitSet(10)创建了BitSet The constructor parameter is just a desired initial capacity (like in ArrayList ). 构造函数参数只是一个所需的初始容量(如在ArrayList )。 It's used as performance hint only. 它仅用作性能提示。

The best solution from the performance point of view is to check nextClearBit(0) >= myLength where myLength is the maximal number of values you want to store in BitSet (you should keep it by yourself). 从性能的角度来看,最佳解决方案是检查nextClearBit(0) >= myLength ,其中myLength是您要在BitSet存储的最大值数(您应该自己保留它)。 This may work faster than cardinality() if the result is false . 如果结果为false这可能比cardinality()更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM