哈希表
哈希表保存雇员
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.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");
int id = scanner.nextInt();
hashTab.findEmpById(id);
break;
case "exit":
scanner.close();
System.exit(0);
default:
break;
}
}
}
}
public HashTab{
private EmpLinkedList[] empLinkedListArray;
public HashTab(int size){
empLinkedListArray = new EmpLinkedList[size];
for(int i=0;i<size;i++){
empLinkedListArray[i] = new EmpLinkedList();
}
}
public void add(Emp emp){
int empLinkedListNo = hashFun(emp.id);
empLinkedListArray[empLinkedListNo].add(emp);
}
public void list(){
for(int i=0;i<size;i++){
empLinkedListArray[i].list(i);
}
}
public int hashFun(int id){
return id%size;
}
public void findEmpById(int id){
int empLinkedListNo = hashFun(id);
Emp emp = empLinkedListArray[empLinkedListNo].findEmpById(id);
if(emp!=null){
System.out.printf("在%d链表中找到id=%d\n",empLinkedListNo,id);
}else{
System.out.println("hashtab没有找到'");
}
}
}
class Emp{
public int id;
public String name;
public Emp next;
public Emp(int id,String name){
this.id = id;
this.name = name;
}
}
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+"链表为空");
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;
}
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;
}
curEmp = curEmp.next;
}
return curEmp;
}
}