使用哈希表管理雇员信息:
package calculate;
import java.util.Scanner;
public class HashTab {
public static void main(String[] args) {
//创建哈希表
HashTableDemo hashTableDemo = new HashTableDemo(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.nextLine();
switch (key) {
case "add":
System.out.println("输入id");
int id = scanner.nextInt();
System.out.println("输入name");
String name = scanner.nextLine();
//创建雇员
Emp emp = new Emp(id, name);
hashTableDemo.add(emp);
break;
case "list":
hashTableDemo.list();
break;
case "find":
System.out.println("请输入要查找的id");
id = scanner.nextInt();
hashTableDemo.findEmpById(id);
break;
case "exit":
scanner.close();
System.exit(0);
break;
default:
break;
}
}
}
}
//创建哈希表
class HashTableDemo{
private EmpLinkedList[] empLinkedList;
private int size; //表示有多少条链表
//构造器
public HashTableDemo(int size) {
//初始化empLinkedList
empLinkedList = new EmpLinkedList[size];
//这时不要忘了分别初始化每个链表
for (int i = 0; i < empLinkedList.length; i++) {
empLinkedList[i] = new EmpLinkedList();
}
}
//添加雇员
public void add(Emp emp) {
//根据员工的id得到该员工应该加入哪条链表
int empLinkedListNo = hashFun(emp.id);
//将emp添加到对应的链表中
empLinkedList[empLinkedListNo].add(emp); //用EmpLinkedList中的方法
}
//遍历所有链表,遍历hashtable
public void list() {
for (int i = 0; i < size; i++) {
empLinkedList[i].list(i); //用EmpLinkedList中的方法
}
}
//编写散列函数(取模法)
public int hashFun(int id) {
return id % size;
}
//根据输入id查找雇员
public void findEmpById(int id) {
//使用散列函数决定到哪条链表找
int empLinkedListNo = hashFun(id);
Emp emp = empLinkedList[empLinkedListNo].findEmpById(id);
if (emp != null) {
System.out.println("在第"+empLinkedListNo+1+"条链表找到了"+id);
}else
System.out.println("没有找到");
}
}
//雇员类
class Emp{
public int id;
public String name;
public Emp next;
public Emp(int id, String name) {
super();
this.id = id;
this.name = name;
}
}
//链表存储数据
class EmpLinkedList{
//头指针,指向第一个Emp
private Emp head;
//添加雇员到链表
//1.当添加雇员时,id是自增长,从小到大,直接将雇员添加到最后
public void add(Emp emp) {
//如果添加第一个
if (head == null) {
head = emp;
return;
}
//如果不是第一个,使用辅助指针定位到最后
Emp curEmp = head;
while (true) {
if (curEmp.next == null) { //说明已经到最后
break;
}
curEmp = curEmp.next;//后移
}
//退出时直接加入链表
curEmp.next = emp;
}
//遍历链表雇员信息
public void list(int no) {
if (head == null) { //说明当前链表为空
System.out.println("第"+no+1+"条链表为空");
}
System.out.print("第"+no+1+"条链表信息:");
Emp curEmp = head;
while (true) {
System.out.println(curEmp.id+","+curEmp.name);
if (curEmp.next == null) { //已经是最后节点
break;
}
curEmp = curEmp.next; //后移
}
}
//根据id查找雇员
//如果查找到就返回Emp,没找到就返回null
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;
}
}