布隆过滤器


package org.jf.alg;

import java.util.BitSet;

/**
*
*
*
* @author chenjf
*
*/
public class BloomFilter
{

private BitSet bit_array ;
private final int MAX_SIZE ;

public BloomFilter(int size)
{

this(size,2000000000);
}

public BloomFilter(int size,int max)
{
bit_array = new BitSet(size);
if(max % 8 ==0)
MAX_SIZE = max / 8;
else
MAX_SIZE = max / 8 +1;
}


public boolean filter(String value)
{
int hash1 = this.hashCode1(value);
int hash2 = this.hashCode2(value);
int hash3 = this.hashCode3(value);
int hash4 = this.hashCode4(value);
if(this.bit_array.get(hash1) &&
this.bit_array.get(hash2) &&
this.bit_array.get(hash3) &&
this.bit_array.get(hash4))
return true;

else
{
this.bit_array.set(hash1);
this.bit_array.set(hash2);
this.bit_array.set(hash3);
this.bit_array.set(hash4);

return false;
}
}

public boolean contains(String value)
{
int hash1 = this.hashCode1(value);
int hash2 = this.hashCode2(value);
int hash3 = this.hashCode3(value);
int hash4 = this.hashCode4(value);
if(this.bit_array.get(hash1) &&
this.bit_array.get(hash2) &&
this.bit_array.get(hash3) &&
this.bit_array.get(hash4))
return true;

return false;
}


private int hash(String value/*,int cap*/,int seed)
{
int result = 0;
int len = value.length();
for(int i =0 ;i<len;i++)
{
result = seed*result + value.charAt(i);
}
return /*Math.abs((cap - 1) & result )*/ Math.abs( result % this.MAX_SIZE );
}

private int hashCode1(String value)
{
return hash(value,13);
}

private int hashCode2(String value)
{
return hash(value,17);
}

private int hashCode3(String value)
{
return hash(value,31);
}

private int hashCode4(String value)
{
return hash(value,41);
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值