提升数据查找速度,减少数据库压力。
package hashtab;
import java.util.HashMap;
import java.util.Scanner;
public class HashTabDemo {
public static void main(String[] args){
//创建Hsth表
HashTab hashMap = new HashTab(7);
String key="";
Scanner sc= new Scanner(System.in);
while (true){
System.out.println("add:添加");
System.out.println("list:显示");
System.out.println("find:查找");
System.out.println("exit:退出");
key = sc.next();
switch (key){
case "add":
System.out.println("输入id:");
int id = sc.nextInt();
System.out.println("输入名字:");
String name = sc.next();
//创建雇员
Emp emp = new Emp(id,name);
hashMap.add(emp);
break;
case "list":
hashMap.list();
break;
case "find":
System.out.println("请输入查找的id:");
id = sc.nextInt();
hashMap.findEmpById(id);
break;
case "exit":
sc.close();
System.exit(0);
default:
break;
}
}
}
}
//创建HashTab管理多条链表
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);
//将emp添加到链表
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\t",empLinkedListNo,id);
}else {
System.out.println("在hash表没找到");
}
}
//编写散列函数,使用取模法
public int hashFun(int id){
return id % size;
}
}
//表示一个雇员
class Emp{
public int id;
public String name;
public Emp next; //null
public Emp(int id, String name) {
this.id = id;
this.name = name;
}
}
//创建EmpLinkedList,表示链表
class EmpLinkedList{
private Emp head; //null
//添加雇员到链表
/**
* 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+"链表为空...");
return;
}
System.out.println("第"+no+"链表信息为:");
Emp curEmp = head;
while (true){
System.out.printf("=> id=%d name=%s\t",curEmp.id,curEmp.name);
if (curEmp.next == null){
break;
}
curEmp = curEmp.next;
}
}
//根据id查找雇员
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;
}
}