哈希表是根据关键码值而直接进行访问的数据结构,通过吧关键码值映射到表中的一个位置来访问记录,以加快查找的速度。
韩老师这次是通过一个google的面试上机题:通过哈希表来存储员工信息
首先写一个员工类和员工链表
//写一个员工类
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 temp=head;
while (true){
if (temp.next==null){
break;
}
temp=temp.next;
}
}
//显示员工
public void list(){
if (head==null){
System.out.println("kong");
return;
}
System.out.println("当前信息为");
Emp temp=head;
while (true){
System.out.println(temp.id+"--"+temp.name);
if (temp.next==null){
break;
}
temp=temp.next;
}
}
}
然后写一个哈希表
//哈希表:数组+链表
class Hashtab{
private EmpLinkedList[] empLinkedListsArr;
private int size;
public Hashtab(int size){
this.size=size;
empLinkedListsArr =new EmpLinkedList[size];
for (int i = 0; i <size ; i++) {
empLinkedListsArr[i]=new EmpLinkedList();
}
}
public void add(Emp emp){
int emplistNo=hashFun(emp.id);
empLinkedListsArr[emplistNo].add(emp);
}
public void list(){
for(int i=0;i<size; i++){
empLinkedListsArr[i].list();
}
}
public int hashFun(int id){
return id%size;
}
最后测试
public class HashDemo {
public static void main(String[] args) {
Hashtab hashtab=new Hashtab(8);
String str="";
Scanner scanner=new Scanner(System.in);
while (true){
System.out.println("add 添加");
System.out.println("list 显示");
System.out.println("exit 退出");
str=scanner.next();
switch (str){
case "add":
System.out.println("please input id");
int id=scanner.nextInt();
System.out.println("input name");
String name=scanner.next();
Emp emp=new Emp(id,name);
hashtab.add(emp);
break;
case "list":
hashtab.list();
break;
case "exit":
scanner.close();
System.exit(1);
}
}
}
}