Java 简明教程
Java BitSet Class
Introduction
Java BitSet 类创建了一个特殊类型,可保存位值。BitSet 数组可以根据需要增加大小。这使其类似于位向量。这是一个旧类,但是它已经过 Java 2 1.4 版的完全重构。
The Java BitSet class creates a special type of array that holds bit values. The BitSet array can increase in size as needed. This makes it similar to a vector of bits. This is a legacy class but it has been completely re-engineered in Java 2, version 1.4.
Java BitSet 类实现了一个根据需要增长的位向量。以下是有关 BitSet 的重要要点——
The Java BitSet class implements a vector of bits that grows as needed.Following are the important points about BitSet −
-
A BitSet is not safe for multithreaded use without external synchronization.
-
All bits in the set initially have the value false.
-
Passing a null parameter to any of the methods in a BitSet will result in a NullPointerException.
Class declaration
以下是 java.util.BitSet 类的声明——
Following is the declaration for java.util.BitSet class −
public class BitSet
extends Object
implements Cloneable, Serializable
Methods inherited
此类从以下类中继承方法:
This class inherits methods from the following classes −
-
java.util.Object
Creating a BitSet and Performing Operations on BitSets Example
以下程序展示了位集数据结构支持的几种方法 −
The following program illustrates several of the methods supported by BitSet data structure −
import java.util.BitSet;
public class BitSetDemo {
public static void main(String args[]) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i = 0; i < 16; i++) {
if((i % 2) == 0) bits1.set(i);
if((i % 5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
这会产生以下结果 −
This will produce the following result −