Java入門-BitSet的使用

在使用PAT-Tree的中文實現中需要用到大量的位運算,BitSet在效率上的表現可能尚待商榷,不過拿來做實驗是沒有問題的。

 

在Java的文檔中說明了BitSet實現了Vector接口,是一個可按需增長的存儲位的數據結構,位的值位布爾型,初始大小爲64bit,初始值均爲“false”。

常用方法:

  • void set(int bitIndex)、void set(int bitIntex, boolean value) : 將bitIndex位置的值設爲“true”或者給定的值
  • boolean get(int bitIndex) :獲取bitIndex位置處的值
  • BitSet get(int fromIndex, int toIndex) :以BitSet存儲返回fromIndex與toIndex區間之間的值
  • void clear()、void clear(int bitIndex)、void clear(int fromIndex, int toIndex) :置整個BitSet/相應位置/區間的值爲“false”
  • int length() :BitSet的邏輯大小(實際使用大小),值爲“true”最大的索引位加1
  • int size() :BitSet的實際大小,默認爲64
  • and(BitSet set)、andNot(BitSet set) … :與另一BitSet相應的邏輯位運算
  • String toString() :返回值爲“true”的位置的String對象,如第1和第10位爲“true”,其他位置爲“false”,則返回{1, 10}

應用實例:下面的代碼將字符轉換爲與編碼對應的二進制字符串:

package org.eone.test;
 
import java.util.BitSet;
 
public class TestBitSet {
 
    private static String toBitSet(String str){
        String result = "[";
        BitSet bitSet = new BitSet();
        byte[] strBits = str.getBytes();
        for(int i = 0; i< strBits.length * 8; i++){
            if((strBits[i / 8] & (128 >> (i % 8))) > 0){
                bitSet.set(i);
            }
        }
        for(int i = 0; i < bitSet.length(); i++){
            if(bitSet.get(i))
                result += "1";
            else
                result +="0";
        }
        result += "]";
        return result;
    }
 
    public static void main(String[] args) {
        String str = "測試一下";
        System.out.println(toBitSet(str));
    }
 
}
 使用時還需注意,在多線程情況下要注意線程安全問題。
發佈了125 篇原創文章 · 獲贊 0 · 訪問量 6283
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章