8哈希表
作者:互联网
哈希表
基本介绍
哈希表实现
package com.company.hash;
import javafx.css.Size;
import javax.sound.midi.Soundbank;
/**
* @Function :
* date 2021/5/18 - 16:04
* How :
*/
public class HashTable {
public static void main(String[] args) {
HashTab hashTab = new HashTab(24);
for (int i = 0; i < 200; i++) {
hashTab.add(new Employ(i,"employ"+i,"男"));
}
hashTab.list();
Employ employById = hashTab.findEmployById(125);
System.out.println("===========================================");
System.out.println(employById);
System.out.println("===========================================");
}
}
//hash表
class HashTab{
private EmployLinkedList[] employLinkedArray;
int size;
public HashTab(int size) {
this.size =size;
this.employLinkedArray = new EmployLinkedList[this.size];
for (int i = 0; i < employLinkedArray.length; i++) {
employLinkedArray[i] = new EmployLinkedList();
}
}
public void add(Employ emp){
int num = hashFunc(emp.id);
employLinkedArray[num].add(emp);
}
public int hashFunc(int id){
return id % this.size;
}
public void list(){
for (int i = 0; i < size; i++) {
System.out.println();
EmployLinkedList tempEmp = employLinkedArray[i];
tempEmp.list(i);
System.out.println();
}
}
public Employ findEmployById(int id){
int Arrayid = id % size;
Employ employById = employLinkedArray[Arrayid].findEmployById(id);
return employById;
}
}
//雇员
class Employ{
public int id;
public String name;
public String sex;
public Employ nextNode;
public Employ() {
}
public Employ(int id, String name, String sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
@Override
public String toString() {
return "Employ{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex ;
}
}
//链表
class EmployLinkedList{
private Employ headNode;
public EmployLinkedList() {
this.headNode = null;
}
public void add(Employ emp){
if (headNode == null){
headNode = emp;
return;
}
Employ tempEmp = headNode;
while (true){
if (tempEmp.nextNode == null){
break;
}
tempEmp = tempEmp.nextNode;
}
tempEmp.nextNode = emp;
}
public void list(int no){
no++;
System.out.println("第"+no+"个链表");
if (headNode == null){
System.out.println("空!");
return;
}
Employ tempEmp = headNode;
while (true){
System.out.printf(tempEmp.toString());
System.out.println();
if (tempEmp.nextNode == null){
break;
}
tempEmp = tempEmp.nextNode;
}
}
public Employ findEmployById(int id){
Employ crrent = headNode;
while (true){
if (crrent.id == id){
return crrent;
}
if (crrent.nextNode == null){
System.out.println("未找到");
return null;
}
crrent = crrent.nextNode;
}
}
}
后记
未实现 改 删功能
标签:int,System,id,Employ,哈希,tempEmp,public 来源: https://www.cnblogs.com/jsxz/p/15595388.html