开放地址法意思是数组中的所有空间都对要插入的节点开放,当两个键值计算出的索引值一样的时候,后插入的数据将会顺次找到一个空的数组的索引插入。
package ch12;
import java.math.BigInteger;
public class HashTable {
private Info[] arr;
public HashTable() {
arr = new Info[100];
}
public HashTable(int maxsize) {
arr = new Info[maxsize];
}
public Info[] getArr() {
return arr;
}
public void setArr(Info[] arr) {
this.arr = arr;
}
// 插入数据
public void insert(Info info) {
// 获取当前的关键字的哈希数
int hashcode = hashCode(info.getKey());
// 当这个索引已经被占用,而且里面是一个未被删除的数据
while (arr[hashcode] != null && arr[hashcode].getValue() != null) {
// 查找下一个
hashcode++;
// 循环数组
hashcode %= arr.length;
}
arr[hashcode]=info;
}
// 查找数据
public Info find(String key) {
int hashcode = hashCode(key);
// 这个参数为了记录进入时的索引,查找一周后不在查找
int index = hashcode;
while (arr[hashcode] != null) {
if (arr[hashcode].getKey().equals(key) && arr[hashcode].getKey() != null) {
return arr[hashcode];
}
++hashcode;
hashcode %= arr.length;
System.out.println("查找——————————————");
if (hashcode == index) {
return null;
}
}
return null;
}
// 删除数据
public String delete(String key) {
int hashcode = hashCode(key);
// 这个参数为了记录进入时的索引,查找一周后不在查找
int index = hashcode;
while (arr[hashcode] != null) {
if (arr[hashcode].getKey().equals(key)) {
Info info = arr[hashcode];
info.setValue(null);
return info.getKey();
}
hashcode++;
hashcode %= arr.length;
if (hashcode == index) {
return null;
}
System.out.println("删除——————————————————");
}
return null;
}
// 将键值转化为整数值
// 迷得乘积之后压缩可选值
public int hashCode(String key) {
// 大整数解决整数类型幂越界
BigInteger hashVal = new BigInteger("0");
BigInteger pow27 = new BigInteger("1");
for (int i = key.length() - 1; i >= 0; i--) {
int letter = key.charAt(i) - 96;
BigInteger letterB = new BigInteger(String.valueOf(letter));
hashVal = hashVal.add(letterB.multiply(pow27));
pow27 = pow27.multiply(new BigInteger(String.valueOf(27)));
}
return hashVal.mod(new BigInteger(String.valueOf(arr.length))).intValue();
}
public static void main(String[] args) {
HashTable hashTable = new HashTable(2);
hashTable.insert(new Info("a", "张三"));
hashTable.insert(new Info("cg", "李四"));
System.out.println(hashTable.find("a").getValue());
System.out.println(hashTable.find("cg").getValue());
System.out.println(hashTable.arr[0].getKey());
System.out.println(hashTable.arr[1].getKey());
}
}
/**
*
*/
package ch12;
/**
* @author lixin
* @date 2018年7月31日
* @Description TODO
*/
public class Info {
private String key;
private String value;
public Info(String key, String value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}