哈希表的具体实现:
package com.model.hashtable; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/7/13 9:49 * 演示哈希表的具体实现: * 保存员工的信息 */ public class HashTableDemo01 { public static void main(String[] args) { HashTable table = new HashTable(7); Emp emp = new Emp(1, "张紫韩1"); table.add(emp); table.add(new Emp(2,"张紫韩2")); table.add(new Emp(3,"张紫韩3")); table.add(new Emp(8,"张紫韩3")); table.list(); System.out.println(table.findEmpById(9)); emp.name="张三"; table.update(emp); table.list(); table.deleteById(2); table.deleteById(1); table.list(); } } class HashTable{ private LinkedList[] hashTable; private int size; public HashTable(int size) {//初始化HashTable hashTable=new LinkedList[size]; this.size=size; //初始换链表,因为数组中每条链表现在都是null,不能进行操作,需要进行初始化, //可以赋值给他一个链表,但是不能给他加入节点 for (int i = 0; i < size; i++) { hashTable[i]=new LinkedList(); } } //编写一个散列函数 private int hashFun(int id){ return id%size; } // 添加员工 public void add(Emp emp){ int i = hashFun(emp.id); hashTable[i].add(emp); } // 根据id好查找员工信息 public Emp findEmpById(int id){ int i = hashFun(id); Emp emp = hashTable[i].find(id); return emp; } // 修改员工的信息 public void update(Emp emp){ int i = hashFun(emp.id); hashTable[i].update(emp); } // 根据id号删除员工 public void deleteById(int id){ int i = hashFun(id); hashTable[i].delete(id); } // 遍历所有的员工信息 public void list(){ for (int i = 0; i < size; i++) { hashTable[i].show(i); } } } class LinkedList{ public Emp head; public boolean isEmpty(){ if (head==null){ return true; } return false; } public void add(Emp emp){ if (isEmpty()){ head=emp; }else { Emp temp=head; while (temp.next!=null){ temp=temp.next; } temp.next=emp; } } public Emp find(int id){ if (isEmpty()){ System.out.println("链表为空"); return null; }else { Emp temp=head; while(temp!=null){ if (temp.id==id){ return temp; } temp=temp.next; } } System.out.print("没找到此员工的信息"); return null; } public void update(Emp emp){ if (isEmpty()){ return; }else { Emp temp=head; while(temp!=null){ if (temp.id==emp.id){ temp.name=temp.name; System.out.print("修改成功"); return; } temp=temp.next; } System.out.println("没有找到此员工,无法进行修改"); } } public void delete(int id){ if (isEmpty()){ return; }else if(head.id==id){ head=head.next; return; }else { Emp temp=head; while(temp.next!=null){ if (temp.next.id==id){ temp.next=temp.next.next; return; } temp=temp.next; } } } public void show(int num){ if (isEmpty()){ System.out.println("哈希表的"+num+"号链表信息为空"); return; }else { System.out.print("哈希表的"+num+"号链表信息"); Emp emp=head; while (emp!=null){ System.out.print(emp.toString()+"=>\t"); emp=emp.next; } System.out.println(); } } } class Emp{ public int id; public String name; public Emp next; @Override public String toString() { return "Emp{" + "id=" + id + ", name='" + name + '\'' + '}'; } public Emp(int id, String name) { this.id = id; this.name = name; } public Emp() { } }