海量數據存儲java.util.BitSet的使用

BitSet顧名思義即Bit的一個集合,每個Bit只能取1或0(True或False),是存儲海量數據一個途徑。

而實際上BitSet內部核心是一個long的數組.

由於一個long在java中佔用8個字節,即64位.

由於一個int在java中佔用4個字節,即32位.

long[] result

result[0]  則可以保存

00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000

11111111 111111111 111111111 111111111 111111111 111111111 111111111 111111111
 

package main.lqk;


import org.junit.Test;
 
import java.util.BitSet;
import java.util.Date;
import java.util.Random;
 
/**
 * 有1千萬個隨機數,隨機數的範圍在1到1億之間。
 * 現在要求寫出一種算法,將1到1億之間沒有在隨機數中的數求出來?
 */
public class BitSetTest2 {
    public static final int NUM = 10000000;//10;
    public static final int NUM2 = 10 * NUM;
 
    @Test
    public void test() {
        int[] input = new int[NUM2 + 1];
        Random random = new Random();
        for (int i = 1; i < NUM + 1; i++) {
            input[random.nextInt(NUM2) + 1] = 1;
        }
        for (int i = 1; i < NUM2 + 1; i++) {
            if (input[i] == 0)
                System.out.println(i);
        }
    }
 
    @Test
    public void test2() {
        Boolean[] input = new Boolean[NUM2 + 1];
        Random random = new Random();
        for (int i = 1; i < NUM + 1; i++) {
            input[random.nextInt(NUM2) + 1] = true;
        }
        for (int i = 1; i < NUM2 + 1; i++) {
            if (input[i] == false)
                System.out.println(i);
        }
    }
 
    @Test
    public void test3() {
        BitSet input = new BitSet(NUM2 + 1);
        Random random = new Random();
        for (int i = 0; i < NUM + 1; i++) {
        	if(i % 1000000 == 0)System.out.println(new Date());
            input.set(random.nextInt(NUM2) + 1);
        }
        System.out.println();
        int j = 1;
        for (int i = 1; i < NUM2 + 1; i++) {
            if (!input.get(i)) {
                if (j++ % 10 != 0)
                    System.out.print(i + ",");
                else {
                    j = 1;
                    System.out.println(i);
                }
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章