跟着网上的文章写了一遍哈希表的实现,本质上存储结构还是链表,所以有链表基础的同学就很容易上手了
主要流程就是根据key来进行哈希桶的分配,每个桶内有一个链表,分配完桶就进行正常的链表操作即可
public class Node {
// key、value模拟键值对的数据
public Integer key;
public String value;
// 下一节点的引用
public Node next;
public Node() {
}
public Node(int key, String value) {
this.key = key;
this.value = value;
}
}
public class linkedList {
private Node root;
public linkedList(Node node){
this.root = node;
}
public void add(int key,String value){
Node node = root;
while (node.next != null){
if (node.next.key == key){
return;
}
node = node.next;
}
node.next = new Node(key,value);
}
public boolean delete(int key){
Node node = root;
if (root.key == key){
root = root.next;
return true;
}
while (node.next != null){
if (node.next.key == key){
node.next = node.next.next;
return true;
}
node = node.next;
}
return false;
}
public String get(int key){
if (root.key == key){
return root.value;
}
Node node = root;
while (node.next != null){
if (node.next.key == key){
return node.next.value;
}
node = node.next;
}
return null;
}
public void show(){
Node node = root;
while (node != null){
System.out.println(node.value);
node = node.next;
}
}
}
public class HashTable {
private linkedList[] lists; //这个linkedList是自己写的类不是自带的那个linkedList
private int size;
public HashTable(int size){
this.size = size;
lists = new linkedList[size];
}
public void put(int key,String value){
int i = key % size;
if (lists[i] == null){
lists[i] = new linkedList(new Node(key,value));
}else {
lists[i].add(key,value);
}
}
public boolean delete(int key){
int i = key % size;
if (lists[i] != null){
return lists[i].delete(key);
}
return false;
}
public String get(int key){
int i = key % size;
if (lists[i] != null){
return lists[i].get(key);
}
return null;
}
public void show(){
for (int i = 0; i < size; i++) {
if (lists[i] != null){
lists[i].show();
}
}
}
}
public class main {
public static void main(String[] args) {
HashTable hashTable = new HashTable(10);
hashTable.put(1,"TestA1");
hashTable.put(2,"TestA2");
hashTable.put(3,"TestA3");
hashTable.put(11,"TestB1");
hashTable.put(12,"TestB2");
hashTable.put(13,"TestB3");
hashTable.delete(1);
hashTable.delete(11);
System.out.println(hashTable.get(2));
System.out.println(hashTable.get(3));
hashTable.show();
}
}



