哈希表介绍
散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。
使用数组加链表实现散列表
代码实现
package hashtable;
import java.util.Scanner;
public class HashTabDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashTab hashTab = new HashTab();
char key = ' ';
boolean loop = true;
while (loop){
System.out.println("i---init");
System.out.println("l---list");
System.out.println("a---add");
System.out.println("f---find");
System.out.println("e---exit");
key = scanner.next().charAt(0);
switch (key) {
case 'i' -> {
System.out.println("输入初始化大小");
int a = scanner.nextInt();
hashTab.init(a);
}
case 'l' -> hashTab.list();
case 'a' -> {
Emp emp = new Emp();
System.out.println("id:");
int id = scanner.nextInt();
emp.setId(id);
System.out.println("name:");
String name = scanner.next();
emp.setName(name);
hashTab.addEmp(emp);
}
case 'f' -> {
System.out.println("id:");
int id =scanner.nextInt();
hashTab.findById(id);
}
case 'e' -> loop = false;
}
}
}
}
//hashtable
class HashTab{
private EmpLinkedList[] empLinkedListArray;
private int size;
//初始化
public void init(int size){
this.size = size;
empLinkedListArray = new EmpLinkedList[size];
for (int i = 0; i < empLinkedListArray.length; i++) {
empLinkedListArray[i] = new EmpLinkedList();
}
}
//添加操作
public void addEmp(Emp emp){
int index =emp.getId()%size;
empLinkedListArray[index].addEmp(emp);
}
//遍历
public void list(){
for (EmpLinkedList empLinkedList : empLinkedListArray) {
empLinkedList.list();
}
}
//查找
public void findById(int id){
int index = id%size;
empLinkedListArray[index].findById(id);
}
}
//一个雇员信息
class Emp{
private int id;
private String name;
private Emp next;
public Emp() {
}
public Emp(int id, String name, Emp next) {
this.id = id;
this.name = name;
this.next = next;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Emp getNext() {
return next;
}
public void setNext(Emp next) {
this.next = next;
}
}
//一个链表
class EmpLinkedList{
private Emp head;
public EmpLinkedList() {
}
public Emp getHead() {
return head;
}
public void setHead(Emp head) {
this.head = head;
}
//添加操作
public void addEmp(Emp emp){
if (head==null){
head = emp;
}else {
Emp curEmp = head;
while (curEmp.getNext() != null) {
curEmp = curEmp.getNext();
}
curEmp.setNext(emp);
}
}
//遍历操作
public void list(){
if (head==null){
System.out.println("该条链表为空!");
}else {
Emp curEmp = head;
while (curEmp!=null){
System.out.print("id--->"+curEmp.getId()+";"+"name--->"+curEmp.getName());
curEmp = curEmp.getNext();
}
System.out.println();
}
}
//查找操作
public void findById(int id){
if (head==null){
System.out.println("不存在该emp!");
}else {
Emp curEmp = head;
while (curEmp!=null){
if (curEmp.getId()==id){
System.out.println("id--->"+curEmp.getId()+";"+"name--->"+curEmp.getName());
break;
}
curEmp = curEmp .getNext();
}
}
}
}