Java BitSet nextSetBit() 方法

2025年1月7日 | 阅读 2 分钟

Java BitSet 类的 nextSetBit(int fromIndex) 方法返回指定索引开始的第一个设置为 true 的位的索引。如果 BitSet 中没有设置为 true 的位,则返回 -1。

语法

参数

数据类型参数描述
intfromIndex这是 BitSet 中开始检查设置位的索引。

返回值

nextSetBit(int fromIndex) 方法返回下一个设置位的索引,如果没有设置为 true 的位,则返回 -1。

Exception

IndexOutOfBoundsException - 如果指定的索引为负数,则抛出异常。

兼容版本

Java 1.4 及以上版本

示例 1

输出

set bit next or on to 0: 0
set bit next or on to 2: 4

示例 2

如果指定的索引为负数,nextSetBit(int fromIndex) 方法会抛出异常。

输出

bitset: {0, 1, 4, 5, 7}
Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex < 0: -1
	at java.util.BitSet.nextSetBit(Unknown Source)
	at BitSetNextSetBitExample2.main(BitSetNextSetBitExample2.java:15)

示例 3

如果在 BitSet 中找不到设置位,nextSetBit(int fromIndex) 方法将返回 -1。

输出

bitset: {}
set bit on or next to 0: -1