基本介绍
代码实现
package com.xz.hashtab;
import java.util.Scanner;
public class HashTabDemo {
public static void main(String[] args) {
HashTab hashTab = new HashTab(7);
String key = "";
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("add: 添加雇员");
System.out.println("list: 显示雇员");
System.out.println("find: 查找雇员");
System.out.println("exit: 退出系统");
key = scanner.next();
switch (key) {
case "add":
System.out.print("输入id:");
int id = scanner.nextInt();
System.out.print("输入姓名:");
String name = scanner.next();
Emp emp = new Emp(id, name);
hashTab.add(emp);
break;
case "list":
hashTab.list();
break;
case "find":
System.out.print("请输入你想要查找的id:");
id = scanner.nextInt();
hashTab.findEmpById(id);
break;
case "exit":
scanner.close();
System.exit(0);
default:
break;
}
}
}
}
class HashTab {
private EmpLinkedList[] empLinkedLists;
int size;
public HashTab(int size) {
this.empLinkedLists = new EmpLinkedList[size];
for (int i = 0; i < empLinkedLists.length; i++) {
empLinkedLists[i] = new EmpLinkedList();
}
this.size = size;
}
public void add(Emp emp) {
int empLinkedListNo = hashFun(emp.id);
empLinkedLists[empLinkedListNo].add(emp);
}
public void findEmpById(int id) {
int empLinkedListNO = hashFun(id);
Emp emp = empLinkedLists[empLinkedListNO].findEmpById(id);
if (emp != null) {
System.out.println("在第" + (empLinkedListNO + 1) + "条链表中找到 雇员 id = " + id);
} else {
System.out.println("在哈希表中,没有找到该雇员~");
}
}
public void list() {
for (int i = 0; i < empLinkedLists.length; i++) {
empLinkedLists[i].list(i);
}
}
public int hashFun(int id) {
return id % size;
}
}
class EmpLinkedList {
Emp head = null;
public void add(Emp emp) {
if (head == null) {
head = emp;
return;
}
Emp temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = emp;
}
public void list(int no) {
if (head == null) {
System.out.println("第" + (no + 1) + "条链表为空!");
return;
}
System.out.print("第" + (no + 1) + "链表的信息为:");
Emp temp = head;
while (true) {
System.out.print("=> id = " + temp.id + " name = " + temp.name);
if (temp.next == null) {
break;
}
temp = temp.next;
}
System.out.println();
}
public Emp findEmpById(int id) {
if (head == null) {
System.out.println("链表为空");
return null;
}
Emp curEmp = head;
while (true) {
if (curEmp.id == id) {
break;
}
if (curEmp.next == null) {
curEmp = null;
break;
}
curEmp = curEmp.next;
}
return curEmp;
}
}
class Emp {
public int id;
public String name;
public Emp next;
public Emp(int id, String name) {
this.id = id;
this.name = name;
}
}