天天看點

java.util.BitSet的使用

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

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

由于一個long在java中占用8個位元組,即64位.

long[] result

result[0]  則可以儲存

00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000

11111111 111111111 111111111 111111111 111111111 111111111 111111111 111111111

package com.zte.sunquan.demo;

import org.junit.Test;

import java.util.BitSet;
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++) {
            input.set(random.nextInt(NUM2) + 1);
        }
        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);
                }
            }
        }
    }
}