1、介绍
2、代码实现:
package com.hashtab.demo; public class HashTableDemo { public static void main(String[] args) { Emp emp1 = new Emp(1, "aa"); Emp emp2 = new Emp(2, "bb"); Emp emp3 = new Emp(3, "cc"); Emp emp4 = new Emp(4, "dd"); Emp emp5 = new Emp(5, "ee"); HashTab hashTab = new HashTab(5); hashTab.add(emp1); hashTab.add(emp2); hashTab.add(emp3); hashTab.add(emp4); hashTab.add(emp5); hashTab.findEmpByNo(1); hashTab.list(); } } //创建雇员表,表示链表的节点类 class Emp { public int no; public String name; public Emp next; public Emp(int no, String name) { this.no = no; this.name = name; } @Override public String toString() { return "Emp{" + "no=" + no + ", name='" + name + '\'' + '}'; } } //创建链表类 class LinkedList { 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; } temp.next = emp; } //遍历节点 public void list(int i) { if (head == null) { System.out.println("链表为空"); } Emp temp = head; while (true) { if (temp == null) { break; } System.out.println(temp.no + " " + temp.name + " "); temp = temp.next; } System.out.println(); } //根据雇员No编号查询雇员 public Emp findByNo(int no) { if (head == null) { System.out.println("链表为空"); return null; } Emp temp = head; while (true) { if (temp == null) { temp = null; break; } if (temp.no == no) { break; } temp = temp.next; } return temp; } } //创建HashTab类,来管理链表 class HashTab { private LinkedList[] linkedLists; private int size; public HashTab(int size) { this.size = size; linkedLists = new LinkedList[size]; for (int i = 0; i < size; i++) { linkedLists[i] = new LinkedList(); } } //编写散列函数,使用简单取模法 public int hashFun(int id) { return id % size; } //添加雇员 public void add(Emp emp) { //根据雇员的No,决定添加到那一条链表 int LinkedListNO = hashFun(emp.no); linkedLists[LinkedListNO].add(emp); } //遍历链表 public void list() { for (int i = 0; i < size; i++) { linkedLists[i].list(i); } } //根据雇员No查询雇员 public void findEmpByNo(int no) { int LinkedListNO = hashFun(no);//根据No,找到对应的那一个链表 Emp emp = linkedLists[LinkedListNO].findByNo(no); if (emp == null) { System.out.println("没有找到"); } else { System.out.println("该雇员为:" + emp); } } }