Java BitSet的简单使用

Java的BitSet是一个动态增长的位向量,用于存储布尔值,初始全为false。通过BitSet.set(index)可以设置指定位置为true,get(index)检查状态。遍历true位使用for循环结合previousSetBit方法。注意BitSet不是线程安全的,多线程使用需外部同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先给出BitSet的官方说明:

This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.

By default, all bits in the set initially have the value false.

Every bit set has a current size, which is the number of bits of space currently in use by the bit set. Note that the size is related to the implementation of a bit set, so it may change with implementation. The length of a bit set relates to logical length of a bit set and is defined independently of implementation.

Unless otherwise noted, passing a null parameter to any of the methods in a BitSet will result in a NullPointerException.

A BitSet is not safe for multithreaded use without external synchronization.

简单的说就是:

  • BitSet提供了一个动态的根据需要增加的位向量
  • 该位向量每一位的值为布尔值,且初始时都为false
  • 可以通过:bitSet.set(index) 将某一位设为true,该方法不接受null参数
  • BitSet为非同步的

另外

  • 可以通过 bitSet.get(index) 来获取某一位的状态
  • 可以通过 for (int bit = sum.length(); (bit = sum.previousSetBit(bit-1)) >= 0;) {} 方法遍历所有为 true 的位,bit值即为索引值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三更鬼

谢谢老板!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值