哈希表

package A;

public class Emp {//它是盒子
int id;
String name;
Emp next;

public Emp(int id, String name) {
this.id = id;
this.name = name;
}
}

package A;

import java.util.ArrayList;
import java.util.Arrays;

public class EmpLinkedList {//它是一条链
Emp head;
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){
Emp temp=head;
if (temp==null){
System.out.println(no+",empty");
return;
}
while (true){
System.out.print("current list information =>"+temp.id+temp.name);
if (temp.next==null){
break;
}
temp=temp.next;
}
System.out.println();
}

public Emp findEmpById(int id){
if (head==null){
System.out.println("list empty");
return null;
}
Emp curEmp=head;
while (true){
if (curEmp.id==id){
break;
}
if (curEmp.next==null){
curEmp=null;
break;
}
curEmp=curEmp.next;
}
return curEmp;
}
}

package A;

public class HashTable {//旗杆
EmpLinkedList[] empLinkedLists;
int size;
//构造器
public HashTable(int size){
this.size=size;
empLinkedLists=new EmpLinkedList[size];
for (int i = 0; i < size; i++) {
empLinkedLists[i]=new EmpLinkedList();
}
}
public void add(Emp emp){
int emLinkedListNO=hashFun(emp.id);
empLinkedLists[emLinkedListNO].add(emp);
}
public void findEmpById(int id){
int emLinkedListNO=hashFun(id);
Emp emp=empLinkedLists[emLinkedListNO].findEmpById(id);
if (emp!=null){
System.out.printf("在第%d条链表中找到雇员id=%d\n",(emLinkedListNO+1),id);
}else {
System.out.println("在哈希表中,没有找到该雇员~");
}
}
public int hashFun(int id){
return id % size;
}
public void list(){
for (int i = 0; i < size; i++) {
empLinkedLists[i].list(i);//这应该是是method里面的list吧
}
}
}

package A;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;

public class JosePhu {
public static void main(String[] args) {
HashTable hashTable = new HashTable(10);
Scanner scanner = new Scanner(System.in);

while (true){
System.out.println("add,find,list,exit");
String key=scanner.next();
switch (key){
case "add":
System.out.println("input id");
int id=scanner.nextInt();
System.out.println("input name");
String name=scanner.next();
Emp emp = new Emp(id, name);
hashTable.add(emp);
break;
case "list":
hashTable.list();
break;
case "find":
System.out.println("请输入要查找的id");
id=scanner.nextInt();
hashTable.findEmpById(id);
break;
case "exit":
scanner.close();
System.exit(0);
default:
break;
}
}

}
}

哈希表

上一篇:DeploymentConfig和Deployment


下一篇:前端参数到后端被转义问题