public class HashDetect {
private int mod = 7;
private Entry[] table;
//避免hash聚集,可以令步长为大于1 的整数
private int step = 1;
public void initHashTable(int size){
assert(size > 0);
table = new Entry[size];
mod = size;
}
private int hashCode(Object key){
assert(key != null);
return key.hashCode();
}
public void put(Object key, Object value){
int hCode = hashCode(key) % mod;
int start = hCode;
while(table[hCode] != null){
hCode = (hCode + step) % mod;
if(hCode == start){
break;
}
}
if(table[hCode] == null){
table[hCode] = new Entry(key, value);
}else{
System.out.println("Table is already full.");
}
}
public Object get(Object key){
int hCode = hashCode(key) % mod;
int start = hCode;
while(table[hCode] != null){
//大数据下,hash的性能低下的一个重要原因,equals方法的效率问题
//比如字符串for循环比较
//参考暴雪hash
if(key.equals(table[hCode].key)){
return table[hCode].value;
}else{
hCode = (hCode + step) % mod;
}
if(hCode == start){
break;
}
}
return null;
}
/**
* @param args
*/
public static void main(String[] args) {
}
}
hash冲突之线性探测
最新推荐文章于 2022-11-22 18:24:45 发布