bitMap

来源:互联网 发布:淘宝晚礼服推荐 编辑:程序博客网 时间:2024/06/16 17:53

bitMap 因为是用位来存储,相比较其他数据来说比如int ,可以多存31个不同的数据。
bitMap适用场景,将给定一个10亿级的不重复的int型数据集合A,查询某个数据是否在A中。
如果用普通的数组存储或者HashMap,那么内存绝对要爆掉,可以计算一下4*10*10^8/1024/1024/1024=3.7G
如果用bitMap存储计算一下内存10*10^8/8/1024/1024/1024=0.11G
看一下差距.
好了看下bitMap怎么实现的吧,肯定用到了位运算啦

public class BitMap {    //地址偏移  寻找数组的下标     private final byte shift=5;     //掩码   i&mask 等价于 i%32     private final int  mask=0x1F;     int[] a;     BiteMap(int n){         a=new int[n/32+1];     }     //存值     public  void set(int i){         a[i>>>shift]|=(1<<(i&mask));     }     //查找     public boolean find(int i){    try{        if( (a[i>>>shift]&(1<<(i&mask)))>0){            return true;        }else{            return false;        }        }catch(IndexOutOfBoundsException e){            System.out.println("不在范围内");        }         return false;     }     //删除值     public void remove(int i){        a[i>>>shift]&=(~(1<<(i&mask)));     }    public static void main(String[] args) {        //存入10条不同的数据           BitMap map=new   BitMap((int)Math.pow(10, 9));           map.set(1000);           map.set(1024);           map.set(10001);           System.out.println(map.find(1000));           System.out.println(map.find(1001));           System.out.println(map.find(1024));           map.remove(1024);           System.out.println(map.find(1024));      System.out.println("正常的用数组存储所需内存大小为:"+Math.pow(10, 9)*4.0/1024/1024/1024+"G");      System.out.println("用bitMap存储所需的内存大小为:"+Math.pow(10, 9)/1024/1024/8.0/1024+"G");    }}