Java BitSet get() 方法

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

Java BitSet 类的 get() 方法返回位值。BitSet 类中有两个重载的 get() 方法。

1. Java BitSet get(int bitIndex) 方法

get(int bitIndex) 方法返回指定索引处的位值。如果当前 BitSet 中设置了索引 bitIndex,则返回 true,否则返回 false。

2. Java BitSet get(int fromIndex, int toIndex) 方法

get(int bitIndex) 方法返回当前 BitSet 中从指定包含索引 fromIndex 到排除索引 toIndex 的位的新 BitSet。

语法

参数

数据类型参数描述
intbitIndex这是位的索引。
intfromIndex这是位值的起始索引。
inttoIndex这是位值的排除结束索引。

返回值

方法描述
get(int bitIndex)它返回指定索引处的位值。
get(int fromIndex, int toIndex)它返回从指定 fromIndex 到排除的 toIndex 的位的新的 BitSet。

Exception

IndexOutOfBoundsException - 如果以下任何陈述成立

  • 如果任何索引为负数
  • 如果 fromIndex 大于 toIndex。

兼容版本

方法兼容版本
get(int bitIndex)Java 1.0 及以上版本
get(int fromIndex, int toIndex)Java 1.4 及以上版本

Java BitSet get(int bitIndex) 方法示例

示例 1

输出

bitset: {0, 1, 3, 4}
bitset at index 0: true
bitset at index 1: true
bitset at index 2: false

示例 2

如果传递负整数参数,get(int bitIndex) 方法将抛出异常。

输出

bitset: {0, 1, 3, 4}
Exception in thread "main" java.lang.IndexOutOfBoundsException: bitIndex < 0: -1
	at java.util.BitSet.get(Unknown Source)
	at BitSetGetExample2.main(BitSetGetExample2.java:11)

Java BitSet get(int fromIndex, int toIndex) 方法示例

示例 3

输出

bitset: {0, 1, 3, 4}
bitset at index 0,3: {0, 1}

示例 4

如果 fromIndex 大于 toIndex,get(int fromIndex, int toIndex) 方法将抛出异常。

输出

bitset: {0, 1, 3, 4}
Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex: 3 > toIndex: 0
	at java.util.BitSet.checkRange(Unknown Source)
	at java.util.BitSet.get(Unknown Source)
	at BitSetGetExample4.main(BitSetGetExample4.java:12)