数据结构与算法-java-哈希表
什么是哈希表
散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。
给定表M,存在函数f(key),对任意给定的关键字值key,代入函数后若能得到包含该关键字的记录在表中的地址,则称表M为哈希(Hash)表,函数f(key)为哈希(Hash) 函数。

其实可以这样理解,哈希表就像一个缓冲层

下面来看一个案例

大致可以分析如下

package hashTable;
import java.util.Scanner;
//表示一个雇员
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; //默认为null
//add
public void add(Emp emp)
{
//如果是添加第一个
if(head ==null)
{
head=emp;
return;
}
//不是第一个
Emp temp = head;
while (true)
{
if(temp.next==null)
{
//说明到最后了
break;
}
temp=temp.next; //后移
}
//while退出时一定为最后,指向加入链表就行了
temp.next=emp;
}
public void show(){
if(head==null)
{
System.out.println("当前链表为空");
return;
}
System.out.println("当前链表信息为");
Emp temp=head;
while (true)
{
System.out.printf("=>id=%d name=%s \t",temp.id,temp.name);
if (temp.next == null) {
break;
}
temp=temp.next;//后移即++
}
System.out.println();//换行
}
}
//创建hash表,管理多条链表,如图那样
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)
{
int empNo=hashFunc(emp.id);
empLinkedListArray[empNo].add(emp);
}
public void show(){
for (int i=0;i<size;i++)
{
empLinkedListArray[i].show();
}
}
public int hashFunc(int id)
{
return id%size; //通过模判断在hash表的位置
}
}
public class hashTableDemo {
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("show:显示雇员");
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 "show":
hashTab.show();
break;
case "exit":
scanner.close();
break;
default:
break;
}
}
}
}

相关推荐
chenfei0 2020-07-30
范范 2020-07-04
lickylin 2020-04-25
kaixinfelix 2020-10-04
liqinglin0 2020-07-05
清溪算法君老号 2020-06-25
MLXY 2020-06-18
深思千年 2020-06-10
码墨 2020-05-29
ipqtjmqj 2020-05-19
waitwolf 2020-05-12
rongxionga 2020-05-06
yangjingdong00 2020-05-04
kaixinfelix 2020-05-01
fsl 2020-04-29
凌风郎少 2020-04-23
无能力者只知抱怨 2020-04-23
soyo 2020-04-23