【1】HashTable原理

【2】说明
- 通过数组加链表的方式实现
- 只实现了添加和打印方法,其余方法类似
【3】代码:
package algorithm.hashTable;
public class MyHashTable {
public static void main(String[] args) {
Hash hashTable = new Hash(5);
Element e1 = new Element(2, "zjComing");
Element e2 = new Element(45, "beijing");
Element e3 = new Element(12, "ttttttt");
Element e4 = new Element(60, "mmmmmmm");
hashTable.add(e1);
hashTable.add(e2);
hashTable.add(e3);
hashTable.add(e4);
hashTable.show();
}
}
class Element {
int id;
String name;
Element next;
public Element(int id, String name) {
this.id = id;
this.name = name;
}
}
class ElemLinkedList {
Element head;
public void add(Element e) {
if (head == null) {
head = e;
return;
}
Element temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = e;
}
public void show(int no) {
Element temp = head;
while (temp != null) {
System.out.printf("第 %d 个链表=> id是:%d 姓名:%s\t", no + 1, temp.id, temp.name);
temp = temp.next;
}
System.out.println();
}
}
class Hash {
private ElemLinkedList[] list;
private int size;
public Hash(int size) {
this.size = size;
list = new ElemLinkedList[size];
for (int i = 0; i < size; i++) {
list[i] = new ElemLinkedList();
}
}
public void add(Element e) {
int no = getNo(e.id);
list[no].add(e);
}
public void show() {
for (int i = 0; i < size; i++) {
list[i].show(i);
}
}
private int getNo(int id) {
return id % size;
}
}