哈希表思路:
1.需要一个数组,数组中存取的是一个链表,这个链表可以没有表头。
2.需要一个哈希计算的方法,决定传入的数据存在哪里
public class HashTable {
public static void main(String[] args) {
HashTable hashTable = new HashTable(7);
User user = new User(1,18,"张三");
hashTable.addUser(1,user);
hashTable.findId(1);
}
private int maxSize;
private HashHeadList[] hashTable;
public HashTable(int max) {
this.maxSize = max;
hashTable = new HashHeadList[max];
for (int i = 0; i < max; i++) {
hashTable[i] = new HashHeadList();
}
}
public void addUser(int id, User user){
hashTable[hashValue(id,this.maxSize)].add(user);
}
public void showHash(){
for (int i = 0; i < hashTable.length; i++) {
System.out.print("第"+i+"条");
hashTable[i].showHashTable();
}
}
public int hashValue(int id, int maxSize){
return id % maxSize;
}
public void findId(int id){
int index = hashValue(id,this.maxSize);
hashTable[index].find(id);
}
public void remove(int id){
int index = hashValue(id,this.maxSize);
hashTable[index].remove(id);
}
}
class User{
public int id;
private int age;
private String name;
public User next;
public User(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public void prints(){
System.out.println("id = "+id+", age = "+age+", name = "+name+";");
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
class HashHeadList{
public User head;
public void add(User user){
if (head == null){
head = user;
return;
}
User temp = head;
while (true){
if (temp.next == null){
break;
}
temp = temp.next;
}
temp.next = user;
System.out.println("添加成功");
}
public void showHashTable(){
if (head == null){
System.out.println("当前哈希表为空");
return;
}
User temp = head;
while (true){
temp.prints();
if (temp.next == null){
break;
}
temp = temp.next;
}
}
public void find(int id){
User temp = head;
while (true){
if (head == null){
System.out.println("空");
return;
}
if (temp.id == id){
System.out.println("找到"+id);
return;
}
if (temp.next == null){
return;
}
temp = temp.next;
}
}
public void remove(int id){
if (head == null){
System.out.println("空");
return;
}
User temp = head;
User temp2 = null;
while (true){
if (temp.next == null){
System.out.println("没有找到");
return;
}
if (temp.next.id == id){
temp.next = temp.next.next;
break;
}
temp = temp.next;
}
}
}