gpt4 book ai didi

java - BitSet 长度返回 0

转载 作者:行者123 更新时间:2023-12-02 10:18:17 25 4
gpt4 key购买 nike

我使用 BitSet 来表示数据的时间序列。例如,第一位代表第 1 天,第二位代表第 2 天,依此类推。

当我运行以下代码时,我很困惑,因为它总是返回长度为 0:

BitSet a = new BitSet();
for( int i = 0 ; i < 100 ; i++ ) {
a.set(i, false);
}
System.out.println(a.length());

经过一番尝试后,我看到了它,因为这些值都是假的。我将该位设置为零,因此我假设它会计入长度并且我需要它来计数。有没有办法获得包括 false 和 true 在内的计数?

最佳答案

类 BitSet 有一个 constructor with the desired number of bits .

Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. All bits are initially false.

BitSet.size()

Returns the number of bits of space actually in use by this BitSet to represent bit values. The maximum element in the set is the size - 1st element.

BitSet.cardinality

Returns the number of bits set to true in this BitSet.

BitSet 是一个压缩的位集合,似乎这不是您的需要,因为您必须知道设置为 true 或 false 的位数。

我的建议:

import java.util.ArrayList;
import java.util.List;

public class Main {

public static void main( String[] args ) {
final List<Boolean> bs = new ArrayList<>( 100 );
for( int i = 0; i < 100; ++i ) {
bs.add( Boolean.FALSE );
}
System.err.println( bs.size());
bs.set( 7, Boolean.TRUE );
System.err.println( bs.size());
bs.set( 42, Boolean.TRUE );
System.err.println( bs.size());
}
}

该程序回显 100, 3 次。

关于java - BitSet 长度返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54525663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com