以员工为例:
package d15哈希表;
//员工信息类
public class Info {
private String key;
private String name;
public Info(String key ,String name){
this.key=key;
this.name=name;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package d15哈希表;
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 void insert( Info info){
arr[hashCode(info.getKey())]= info;
}
private 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 Info find (String key ){
return arr[hashCode(key)];
}
}