一、哈希表
1.1 概述
- 散列表(
Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。 - 给定表M,存在函数f(key),对任意给定的关键字值key,代入函数后若能得到包含该关键字的记录在表中的地址,则称表M为哈希(Hash)表,函数f(key)为哈希(Hash) 函数。
- 示意图:
1.2 代码示例
使用链表来实现哈希表。
public class HashTableDemo {
public static void main(String[] args) {
HashTable table = new HashTable(7);
table.add(new Node(1, "data1"));
table.add(new Node(2, "data2"));
table.add(new Node(3, "data3"));
table.foreach();
// 1-linked list is null.
// 2-linked list:{id=1,data=data1}
// 3-linked list:{id=2,data=data2}
// 4-linked list:{id=3,data=data3}
// 5-linked list is null.
// 6-linked list is null.
// 7-linked list is null.
System.out.println("----------------- ");
System.out.println(table.findById(2));
// Node(id=2, data=data2, next=null)
}
}
class HashTable {
private final NodeLinkedList[] arrayLinkedList;
private final int size;
public HashTable(int size) {
this.size = size;
// init array
this.arrayLinkedList = new NodeLinkedList[size];
for (int i = 0; i < arrayLinkedList.length; i++) {
arrayLinkedList[i] = new NodeLinkedList();
}
}
private int hashFun(int id) {
return id % size;
}
public void add(Node node) {
int index = hashFun(node.getId());
this.arrayLinkedList[index].add(node);
}
public void foreach() {
for (int i = 0; i < this.arrayLinkedList.length; i++) {
arrayLinkedList[i].foreach(i);
}
}
public Node findById(int id) {
int index = hashFun(id);
return this.arrayLinkedList[index].findById(id);
}
}
class NodeLinkedList {
private Node head;
public void add(Node node) {
if (null == head) {
this.head = node;
return;
}
Node cur = this.head;
while (null != cur.getNext()) {
// move
cur = cur.getNext();
}
// tail
cur.setNext(node);
}
public void foreach(int id) {
int number = id + 1;
if (null == head) {
System.out.println(number + "-linked list is null.");
return;
}
Node cur = this.head;
while (null != cur) {
System.out.printf(
"%d-linked list:{id=%d,data=%s}\t",
number,
cur.getId(),
cur.getData()
);
cur = cur.getNext();
}
System.out.println();
}
public Node findById(int id) {
if (null == head) {
return null;
}
Node cur = this.head;
while (null != cur) {
if (id == cur.getId()) {
break;
}
cur = cur.getNext();
}
return cur;
}
}
@Setter
@Getter
@ToString
class Node {
private int id;
private Object data;
private Node next;
public Node(int id, Object data) {
this.id = id;
this.data = data;
}
}
二、结束语
“-------怕什么真理无穷,进一寸有一寸的欢喜。”
微信公众号搜索:饺子泡牛奶。