Bitmap java实现

bitmap

实现

Data.java,随机产生数据,注意数据是写到文件里的

import java.io.*;
import java.util.Random;

/**
 * Created by Jason on 2016/4/18.
 */
public class Data {

    public static void generateData(int size) {
        Random rd = new Random();
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("qq.txt"));
            for (int i=0;i"");
                bw.write("\n");
            }
            bw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Bitmap.java

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by Jason on 2016/4/18.
 */
public class BitMap {

    private int array[];
    private final int shift = 5;

    public BitMap(int size) {
        array = new int[size/8+1];
    }

    public void insert(int x) {
        int idx = x >> shift;   // x/32
        int value = x & (1<// x%32
        array[idx] |= 1<// set the valueTH location to 1
    }

    public boolean isExist(int x) {
        int idx = x >> shift;   // x/32
        int value = x & (1<// x%32
        int flag = (array[idx] & (1<// get the valueTH location
        return (flag==1)?true:false;
    }
    //read from file and insert element
    public void insertAll() {
        try {
            BufferedReader br = new BufferedReader(new FileReader("qq.txt"));
            String str = null;
            while ((str=br.readLine())!=null) {
                insert(Integer.valueOf(str));
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        int size = 10000000;
        Data.generateData(size);
        Runtime rt = Runtime.getRuntime();
        System.out.println("当前 Java 虚拟机中占用内存量:" + (rt.totalMemory() - rt.freeMemory())/1000/1000 + "M");
        BitMap bitMap = new BitMap(size);
        System.out.println("当前 Java 虚拟机中占用内存量:" + (rt.totalMemory() - rt.freeMemory())/1000/1000 + "M");

        bitMap.insertAll();
        System.out.println("data generate done!");
        System.out.println(bitMap.isExist(size));
    }

}

输出

当前 Java 虚拟机中占用内存量:9M
当前 Java 虚拟机中占用内存量:14M
data generate done!
false

占用内存大小: int array[size/8+1], 4B * 10000000/8 = 5M

应用

判断某个数据是否存在一千万条数据中,使得内存尽量小,此时采用bitmap数据结构,常数时间查询,内存占用小。

你可能感兴趣的:(算法,数据结构)