Java 教程
一個Bitset類創(chuàng)建一種特殊類型的數(shù)組來保存位值。BitSet中數(shù)組大小會隨需要增加。這和位向量(vector of bits)比較類似。
這是一個傳統(tǒng)的類,但它在Java 2中被完全重新設(shè)計。
BitSet定義了兩個構(gòu)造方法。
第一個構(gòu)造方法創(chuàng)建一個默認(rèn)的對象:
BitSet()
第二個方法允許用戶指定初始大小。所有位初始化為0。
BitSet(int size)
BitSet中實現(xiàn)了Cloneable接口中定義的方法如下表所列:
序號 | 方法描述 |
---|---|
1 |
void and(BitSet set) 對此目標(biāo)位 set 和參數(shù)位 set 執(zhí)行邏輯與操作。 |
2 |
void andNot(BitSet set) 清除此?BitSet?中所有的位,其相應(yīng)的位在指定的?BitSet?中已設(shè)置。 |
3 |
int cardinality( ) 返回此?BitSet?中設(shè)置為?true?的位數(shù)。 |
4 |
void clear( ) 將此 BitSet 中的所有位設(shè)置為?false。 |
5 |
void clear(int index) 將索引指定處的位設(shè)置為?false。 |
6 |
void clear(int startIndex, int endIndex) 將指定的 startIndex(包括)到指定的 toIndex(不包括)范圍內(nèi)的位設(shè)置為 false。 |
7 |
Object clone( ) 復(fù)制此?BitSet,生成一個與之相等的新?BitSet。 |
8 |
boolean equals(Object bitSet) 將此對象與指定的對象進行比較。 |
9 |
void flip(int index) 將指定索引處的位設(shè)置為其當(dāng)前值的補碼。 |
10 |
void flip(int startIndex, int endIndex) 將指定的?fromIndex(包括)到指定的?toIndex(不包括)范圍內(nèi)的每個位設(shè)置為其當(dāng)前值的補碼。 |
11 |
boolean get(int index) 返回指定索引處的位值。 |
12 |
BitSet get(int startIndex, int endIndex) 返回一個新的?BitSet,它由此?BitSet?中從?fromIndex(包括)到?toIndex(不包括)范圍內(nèi)的位組成。 |
13 |
int hashCode( ) 返回此位 set 的哈希碼值。 |
14 |
boolean intersects(BitSet bitSet) 如果指定的?BitSet?中有設(shè)置為?true?的位,并且在此?BitSet?中也將其設(shè)置為?true,則返回 true。 |
15 |
boolean isEmpty( ) 如果此?BitSet?中沒有包含任何設(shè)置為?true?的位,則返回 true。 |
16 |
int length( ) 返回此?BitSet?的"邏輯大小":BitSet?中最高設(shè)置位的索引加 1。 |
17 |
int nextClearBit(int startIndex) 返回第一個設(shè)置為?false?的位的索引,這發(fā)生在指定的起始索引或之后的索引上。 |
18 |
int nextSetBit(int startIndex) 返回第一個設(shè)置為?true?的位的索引,這發(fā)生在指定的起始索引或之后的索引上。 |
19 |
void or(BitSet bitSet) 對此位 set 和位 set 參數(shù)執(zhí)行邏輯或操作。 |
20 |
void set(int index) 將指定索引處的位設(shè)置為?true。 |
21 |
void set(int index, boolean v) ?將指定索引處的位設(shè)置為指定的值。 |
22 |
void set(int startIndex, int endIndex) 將指定的?fromIndex(包括)到指定的?toIndex(不包括)范圍內(nèi)的位設(shè)置為?true。 |
23 |
void set(int startIndex, int endIndex, boolean v) 將指定的?fromIndex(包括)到指定的?toIndex(不包括)范圍內(nèi)的位設(shè)置為指定的值。 |
24 |
int size( ) 返回此?BitSet?表示位值時實際使用空間的位數(shù)。 |
25 |
String toString( ) 返回此位 set 的字符串表示形式。 |
26 |
void xor(BitSet bitSet) 對此位 set 和位 set 參數(shù)執(zhí)行邏輯異或操作。 |
下面的程序說明這個數(shù)據(jù)結(jié)構(gòu)支持的幾個方法:
以上實例編譯運行結(jié)果如下:
Initial pattern in bits1: {0, 2, 4, 6, 8, 10, 12, 14} Initial pattern in bits2: {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14} bits2 AND bits1: {2, 4, 6, 8, 12, 14} bits2 OR bits1: {0, 2, 4, 6, 8, 10, 12, 14} bits2 XOR bits1: {}