package com.dai.hashtab; import java.security.PublicKey; import java.util.Scanner; public class HashTabDemo { public static void main(String[] args) { //创建一个hash表 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("exit: 退出系统"); System.out.println("find: 查找雇员"); key = scanner.next(); switch (key) { case "add": 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 "list": hashTab.list(); break; case "find": System.out.println("请输入查找的id:"); id = scanner.nextInt(); hashTab.findEmpById(id); break; case "exit": scanner.close(); System.exit(0); default: break; } } } } //创建哈希表 class HashTab{ private EmpLinkedList[] empLinkedListArray; private int size; //构造器 public HashTab(int size) { this.size = size; empLinkedListArray = new EmpLinkedList[size]; //这里需要记得初始化每一个链表 for(int i=0;i<size;i++) { empLinkedListArray[i] = new EmpLinkedList(); } } //添加雇员 public void add(Emp emp) { //根据Id,决定添加到哪条链表 int empLinkedListNO = hashFun(emp.id); empLinkedListArray[empLinkedListNO].add(emp); } //遍历所有的链表 public void list() { for(int i=0;i<size;i++) { empLinkedListArray[i].list(i); } } //根据输入的id查找雇员 public void findEmpById(int id) { int empLinkedListNO = hashFun(id); Emp emp = empLinkedListArray[empLinkedListNO].findEmpById(id); if(emp != null) { System.out.printf("在第%d条链表中找到雇员id = %d ", (empLinkedListNO+1), id); }else { System.out.println("在哈希表中,没有找到雇员"); } } //编写散列函数 public int hashFun(int id) { return id % size; } } //表示一个雇员 class Emp{ public int id; public String name; public Emp next; public Emp(int id, String name) { super(); this.id = id; this.name = name; } } //创建一个EmpLinkedList class EmpLinkedList{ private Emp head; 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) +"条链表为空"); return; } System.out.print("第"+ (no+1) +"条链表信息为:"); Emp curEmp = head; while(true) { System.out.printf("=> id =%d name=%s ",curEmp.id, curEmp.name); if(curEmp.next==null) { break; } curEmp = curEmp.next; } System.out.println(); } //根据id查找 //找到返回Emp,找不到返回空 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; } }