九、哈希表
1. 介绍
散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。
也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。
2. 管理雇员图
3. 代码实现
public class Test {
public static void main(String[] args) {
HashTab hashTab = new HashTab(7);
Scanner scanner = new Scanner(System.in);
/* while (true) {
System.out.println("0:添加雇员");
System.out.println("1:显示雇员");
System.out.println("2:退出系统");
int next = scanner.nextInt();
switch (next) {
case 0: {
System.out.println("输入id");
int id = scanner.nextInt();
System.out.println("输入名字");
String name = scanner.next();
Emp emp = new Emp(id, name);
hashTab.add(emp);
break;
}
case 1: {
hashTab.list();
break;
}
case 2: {
return;
}
}
}*/
for (int i = 1; i <= 50; i++) {
Emp emp = new Emp(i, String.valueOf(i));
hashTab.add(emp);
}
hashTab.list();
hashTab.findEmp(51);
}
}
// 雇员
class Emp {
int id;
String name;
Emp next;
public Emp(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Emp{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
// 链表
class EmpLinkedList {
// 头指针
private Emp head; // 默认null
// 添加雇员
// 1. 添加雇员时, id自增长,
public void add(Emp emp) {
if (head == null) {
// 第一次添加
head = emp;
return;
}
Emp temp = head;
while (temp.next != null) {
temp = temp.next;
}
// 退出时,加入尾部
temp.next = emp;
}
// 遍历
public void list(int no) {
if (head == null) {
System.out.println("第"+no+"链表为空");
return;
}
Emp temp = head;
while (temp!= null) {
System.out.println(temp);
temp = temp.next;
}
}
// Id 查找
public Emp findById(int id){
// 判断链表是否为空
int count = 0;
if(head == null)return null;
Emp temp = head;
while (temp != null){
count++;
if(temp.id == id){
break;
}
temp = temp.next;
}
System.out.println("第 "+count+" 找到!!");
return temp;
}
}
// 创建 哈希表,管理
class HashTab {
private EmpLinkedList[] empLinkedLists;
private int size; // 表示多少条链表
public HashTab(int size) {
this.size = size;
this.empLinkedLists = new EmpLinkedList[size];
for (int i = 0; i < empLinkedLists.length; i++) {
empLinkedLists[i] = new EmpLinkedList();
}
}
// 添加雇员
public void add(Emp emp) {
int empListNO = hashFun(emp.id);
// 添加到 取模算出的 对应 的链表中
empLinkedLists[empListNO].add(emp);
}
// 遍历 表
public void list() {
for (int i = 0; i < empLinkedLists.length; i++) {
System.out.println("第 "+i+" 条链表");
empLinkedLists[i].list(i);
System.out.println("-------------------------");
}
}
// 编写散列函数,简单取模
public int hashFun(int id) {
return id % size;
}
public void findEmp(int id){
int NO = hashFun(id);
Emp emp = empLinkedLists[NO].findById(id);
if(emp == null){
System.out.println("第 "+NO+" 条表 没找到");
return;
}
System.out.println("第 "+NO+" 条链表:---"+emp);
}
}