链地址法将数组的每一个元素都替换成一个链表当有相同的hashcode的元素插入时就可以存在数组中的同一个元素的链表的不同节点上了。
/**
*
*/
package ch13;
/**
* @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;
}
@Override
public String toString() {
return "Info [key=" + key + ", value=" + value + "]";
}
}
/**
*
*/
package ch13;
public class Node {
// 将属性设置为public访问,可以不写set、get方法!!!
public Info info;
// 下一节点
public Node next;
public Node() {
super();
}
public Node(Info info) {
super();
this.info = info;
}
public void display() {
System.out.print(this.info.toString() + " ");
}
}
package ch13;
public class LinkList {
public Node first;
public LinkList() {
first = null;
}
/**
* 插入一个结点,在头结点后进行插入
*/
public void insertFirst(Info info) {
Node node = new Node(info);
if (first == null) {
first = node;
} else {
if (first.next != null) {
node.next = first.next;
}
first.next = node;
}
}
/**
* 查找方法
*/
public Node find(String key) {
Node current = first;
while (!key.equals(current.info.getKey())) {
if (current.next == null) {
return null;
}
current = current.next;
}
return current;
}
/**
* 删除方法,根据数据域来进行删除
*/
public Node delete(String key) {
Node current = first;
Node previous = first;
while (!key.equals(current.info.getKey())) {
if (current.next == null) {
return null;
}
previous = current;
current = current.next;
}
if (current == first) {
first = first.next;
} else {
previous.next = current.next;
}
return current;
}
}
package ch13;
import java.math.BigInteger;
/**
*
* @author lixin
* @date 2018年8月1日
* @Description 链地址法
*/
public class HashTable {
public LinkList[] arr;
public HashTable() {
arr = new LinkList[100];
}
public HashTable(int maxsize) {
arr = new LinkList[maxsize];
}
// 插入数据
public void insert(Info info) {
int hashVal = hashCode(info.getKey());
if (arr[hashVal] == null) {
arr[hashVal] = new LinkList();
}
arr[hashVal].insertFirst(info);
}
// 查找数据
public Info find(String key) {
int hashVal = hashCode(key);
return arr[hashVal].find(key).info;
}
// 删除数据
public Info delete(String key) {
int hashVal = hashCode(key);
return arr[hashVal].delete(key).info;
}
// 将键值转化为整数值
// 迷得乘积之后压缩可选值
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();
}
}