九、哈希表
1. 介绍
散列表(Hash table,也叫哈希表),是根据关键码值(Key value)而直接进行访问的数据结构。
也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组叫做散列表。
2. 管理雇员图
3. 代码实现
public class Test {
public static void main(String[] args) {
HashTab hashTab = new HashTab(7);
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 50; i++) {
Emp emp = new Emp(i, String.valueOf(i));
hashTab.add(emp);
}
hashTab.list();
hashTab.findEmp(51);
}
}
class Emp {
int id;
String name;
Emp next;
public Emp(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Emp{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
class EmpLinkedList {
private Emp head;
public void add(Emp emp) {
if (head == null) {
head = emp;
return;
}
Emp temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = emp;
}
public void list(int no) {
if (head == null) {
System.out.println("第"+no+"链表为空");
return;
}
Emp temp = head;
while (temp!= null) {
System.out.println(temp);
temp = temp.next;
}
}
public Emp findById(int id){
int count = 0;
if(head == null)return null;
Emp temp = head;
while (temp != null){
count++;
if(temp.id == id){
break;
}
temp = temp.next;
}
System.out.println("第 "+count+" 找到!!");
return temp;
}
}
class HashTab {
private EmpLinkedList[] empLinkedLists;
private int size;
public HashTab(int size) {
this.size = size;
this.empLinkedLists = new EmpLinkedList[size];
for (int i = 0; i < empLinkedLists.length; i++) {
empLinkedLists[i] = new EmpLinkedList();
}
}
public void add(Emp emp) {
int empListNO = hashFun(emp.id);
empLinkedLists[empListNO].add(emp);
}
public void list() {
for (int i = 0; i < empLinkedLists.length; i++) {
System.out.println("第 "+i+" 条链表");
empLinkedLists[i].list(i);
System.out.println("-------------------------");
}
}
public int hashFun(int id) {
return id % size;
}
public void findEmp(int id){
int NO = hashFun(id);
Emp emp = empLinkedLists[NO].findById(id);
if(emp == null){
System.out.println("第 "+NO+" 条表 没找到");
return;
}
System.out.println("第 "+NO+" 条链表:---"+emp);
}
}
|