Java实现简单哈希表
跟着网上的文章写了一遍哈希表的实现,本质上存储结构还是链表,所以有链表基础的同学就很容易上手了
主要流程就是根据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;
}
/**
* 添加数据,key值必须唯一,如果重复值将被覆盖
* @param key
* @param value
*/
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);
}
/**
* 根据key删除数据
* @param key
* @return
*/
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;
}
/**
* 根据key获取数据
* @param key
* @return
*/
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;
/**
* 构造函数
* @param size
*/
public HashTable(int size){
this.size = size;
lists = new LinkedList[size];
}
/**
* 根据key分配哈希桶再添加到链表内
* @param key
* @param value
*/
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);
}
}
/**
* 根据key分配哈希桶再从链表内删除数据
* @param key
* @return
*/
public boolean delete(int key){
int i = key % size;
if (lists[i] != null){
return lists[i].delete(key);
}
return false;
}
/**
* 根据key分配哈希桶再从链表内获取数据
* @param key
* @return
*/
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();
}
}