1.定义节点
package hash;
public class Student {
/**
* 学生节点类
*/
// 为了方便操作,修饰符全写为pubilc
public int id;
public String name;
// 指向下一个节点的指针
public Student next;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
2.定义链表
package hash;
import spares.SparesArray;
public class StudentLinkedList {
// 头结点
private Student head;
/**
* 添加节点
*/
public void add(Student student) {
// 链表如果为空的话,直接把新加入的赋值给头结点
if (head == null) {
head = student;
return;
}
Student temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
// 追加节点
temp.next = student;
}
/**
* 遍历节点
*/
public void list(int no) {
if (head == null) {
System.out.println("第" + (no + 1) + "个链表为空");
return;
}
Student temp = head;
while (true) {
System.out.printf("id = %d name = %s\t", temp.id, temp.name);
if (temp.next == null) {
break;
}
temp = temp.next;
}
System.out.println();
}
/**
* 根据id查找
*/
public Student findById(int id) {
if (head == null) {
return null;
}
Student temp = head;
while (true) {
if (temp.id == id) {
return temp;
}
if (temp.next == null) {
return null;
}
temp = temp.next;
}
}
}
3.定义哈希表
package hash;
public class HashTable {
private StudentLinkedList[] list;
private int size;
/**
* 初始化哈希表
* @param size
*/
public HashTable(int size) {
this.size = size;
list = new StudentLinkedList[size];
// 把链表放入哈希表中
for (int i = 0; i < size; i++) {
// 数组中每一个元素都是一个链表
list[i] = new StudentLinkedList();
}
}
/**
* 定义哈希函数
*/
public int hashCode(int k) {
return k % size;
}
/**
* 添加元素
*/
public void add(Student student) {
// 寻找应该放入的链表
int hashVal = hashCode(student.id);
// 放入对应链表
list[hashVal].add(student);
}
/**
* 遍历
*/
public void list() {
for (int i = 0; i < size; i++) {
list[i].list(i);
}
}
/**
* 根据编号查询
*/
public void findById(int id) {
int hashVal = hashCode(id);
Student temp = list[hashVal].findById(id);
if (temp == null) {
System.out.println("查无此人");
}else {
System.out.printf("在第%d个链表中找到了学生%d %s", (hashVal+1), temp.id, temp.name);
}
System.out.println();
}
}
4.简单测试
package hash;
public class Test {
public static void main(String[] args) {
HashTable hashTable = new HashTable(5);
Student student1 = new Student(1, "aaa");
Student student2 = new Student(2, "bbb");
Student student3 = new Student(3, "ccc");
Student student4 = new Student(4, "ddd");
Student student5 = new Student(5, "eee");
Student student6 = new Student(6, "fff");
Student student7 = new Student(7, "ggg");
Student student8 = new Student(8, "hhh");
hashTable.add(student1);
hashTable.add(student2);
hashTable.add(student3);
hashTable.add(student4);
hashTable.add(student5);
hashTable.add(student6);
hashTable.add(student7);
hashTable.add(student8);
hashTable.list();
hashTable.findById(1);
hashTable.findById(5);
hashTable.findById(111);
}
}