简易版对整数进行过滤、判断是否已存在
代码如下:
package com.zmx.common.common.utils.bitmap;
import lombok.extern.slf4j.Slf4j;
/**
* @Description: 简易版对整数进行过滤、判断是否已存在
* @ClassName: SimpleBitMapUtil
* @Author zhaomxr
* @Date 2021-12-02 10:30
*/
@Slf4j
public class SimpleBitMap {
/**
* 存储数据 byte数组
*/
private byte[] bytes;
/**
* 数组最大容量
*/
private int capacity;
public SimpleBitMap() {
}
private SimpleBitMap(int capacity) {
this.capacity = capacity;
bytes = new byte[(this.capacity >> 3) + 1];
}
/**
* 新增元素
* @param element
*/
public void add(int element) {
//当前元素所在数组下标 element/8
int index = element >> 3;
//当前元素在byte中bit位置 element%8
int position = element & 0x07;
//将1左移position位后,与原有数据做 | 或运算,指定位置值就变为1
bytes[index] |= 1 << position;
}
/**
* 判断当前元素是否已在BitMap中存在
* @param element
* @return
*/
public boolean contain(int element) {
//当前元素所在数组下标 element/8
int index = element >> 3;
//当前元素在byte中bit位置 element%8
int position = element & 0x07;
return (bytes[index] & (1 << position)) != 0;
}
/**
* 清除当前元素
* @param element
*/
public void clear(int element) {
//当前元素所在数组下标 element/8
int index = element >> 3;
//当前元素在byte中bit位置 element%8
int position = element & 0x07;
//将1左移position位,取反,此时就是0,在与原有元素进行&运算,此位置元素清除为0
bytes[index] &= ~(1 << position);
}
public static void main(String[] args) {
long addStart = System.currentTimeMillis();
SimpleBitMap simpleBitMap = new SimpleBitMap(1000000);
int[] elements = new int[]{1, 3, 5, 6, 12, 4, 16, 12, 56, 34, 3, 12, 44, 22};
for (int i = 0; i < 1000000; i++) {
simpleBitMap.add(i);
}
System.out.println("存储元素用时:" + ""+(System.currentTimeMillis() - addStart));
System.out.println("----------------over----------------");
System.out.println("BitMap占用内存:" + simpleBitMap.bytes.length / 1024 +"KB");
System.out.println("BitMap占用内存:" + simpleBitMap.bytes.length / (1024 * 1024) +"MB");
System.out.println("BitMap占用内存:" + simpleBitMap.bytes.length / (1024 * 1024 * 1024) +"MB");
long start = System.currentTimeMillis();
System.out.println(simpleBitMap.contain(3));
System.out.println(simpleBitMap.contain(500000));
System.out.println(simpleBitMap.contain(702441));
System.out.println("查询元素用时:" + ""+(System.currentTimeMillis() - start));
System.out.println("--------------------------------");
simpleBitMap.clear(3);
System.out.println(simpleBitMap.contain(3));
}
}