package ch15;
// 员工信息类
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 ch15;
import java.math.BigInteger;
public class HashTable {
private Info[] arr;
// 默认构造方法
public HashTable() {
arr = new Info[10000];
}
// 指定数组初始化大小
public HashTable(int maxSize) {
arr = new Info[maxSize];
}
// 插入数据,关键字作为索引
public void insert(Info info) {
arr[hashCode(info.getKey())] = info;
}
// 查找数据
public Info find(String key) {
return arr[hashCode(key)];
}
// public int hashCode(String key) {
asc码,缺点abc=bbb=cba之类的
int hashVal = 0;
for(int i = key.length() - 1; i >= 0; i--) {
int letter = key.charAt(i) - 96;
hashVal += letter;
}
return hashVal;
//
幂指数连乘,缺点数字比较大
// int hashVal = 0;
// int pow27 = 1;
// for(int i = key.length() - 1;i >=0; i--) {
// int letter = key.charAt(i) - 96;
// hashVal += letter * pow27;
// pow27 *= 27;
// }
return hashVal;
// return hashVal % arr.length;
//
// }
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();
}
}