明确:
哈希表(Hashtable,也叫散列表)是一种数据结构。
根据关键码值(可以key value)直接进行访问。
它通过把关键码值映射到一个位置来访问记录,以加快查找速度。这个映射函数叫做散列函数。存放记录的数组叫做散列表。
底层:数组+链表/数组+二叉树
代码:
package com;
public class Emp {
int id;
String name;
Emp next;
public Emp(int id, String name) {
this.id = id;
this.name = name;
}
}
package com;
public class EmpLinkedList {
//头结点指向第一个雇员的结点
private Emp head;
public Emp getHead() {
return 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 id){
if(head==null)
{
System.out.println("第"+id+"条链表为空");
return;
}
Emp temp=head;
while(true){
System.out.println("第"+id+"条链表为:"+temp.id+" "+temp.name);
if(temp.next==null)
break;
temp=temp.next;
}
}
//根据id查找
public Emp findById(int id){
if(head==null){
System.out.println("链表为空");
return null;
}
Emp temp=head;
while(true){
if(temp.id==id){
break;
}
if(temp.next==null){
break;
}
temp=temp.next;
}
return temp;
}
}
package com;
//管理多条链表
public class HashTableDemo {
private EmpLinkedList[] empLinkedList;
private int size; //表示有多少链表
public HashTableDemo(int size) {
this.size=size;
//初始化
empLinkedList=new EmpLinkedList[size];
//初始化每条链表
for(int i=0;i<empLinkedList.length;i++){
empLinkedList[i]=new EmpLinkedList();
}
}
public void addChoose(Emp emp){
//根据得到的取模结果,加入
int result=hasFun(emp.id); //方法里调用本类方法
empLinkedList[result].add(emp);
}
//编写散列函数,使用取模法,判断应该加入到那条链表
public int hasFun(int id){
return (id)%size;
}
//遍历所有的链表
public void show(){
for(int i=0;i<size;i++)
{
empLinkedList[i].list(i);
}
}
//根据输入id查找
public void find(int id){
//使用散列确定在那查找
int no=hasFun(id);
Emp emp = empLinkedList[no].findById(id);
if(emp!=null){
System.out.printf("在第%d条链表中找到:%d:",(no+1),id);
}else{
System.out.println("没有找到");
}
}
}
package test;
import com.Emp;
import com.EmpLinkedList;
import com.HashTableDemo;
import java.util.Scanner;
public class testDemo {
public static void main(String[] args) {
HashTableDemo demo=new HashTableDemo(7);
//写一个菜单
String key="";
Scanner scanner = new Scanner(System.in);
while(true){
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);
demo.addChoose(emp);
break;
case "show":
demo.show();
break;
case "find":
System.out.println("请输入要查找的id:");
int value=scanner.nextInt();
demo.find(value);
break;
case "exit":
scanner.close();
System.exit(0);
default:
break;
}
}
}
}