使用Java函数实现哈希表的算法
发布时间:2023-07-06 07:53:10
Java中实现哈希表算法,可以使用Java中的HashMap类来实现。HashMap是基于哈希表实现的,内部使用数组和链表(或红黑树)来处理哈希冲突。
下面是一个简单的实现,用于展示哈希表的基本原理:
public class MyHashTable<K, V> {
// 哈希表的大小
private static final int TABLE_SIZE = 100;
// 哈希表的存储数组
private Entry<K, V>[] table;
// 哈希表的存储项数量
private int size;
// 哈希表的存储项
private static class Entry<K, V> {
private final K key;
private V value;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
public MyHashTable() {
table = new Entry[TABLE_SIZE];
size = 0;
}
// 哈希函数
private int hashFunc(K key) {
return Math.abs(key.hashCode() % TABLE_SIZE);
}
// 向哈希表中插入键值对
public void put(K key, V value) {
int index = hashFunc(key);
Entry<K, V> entry = new Entry<>(key, value);
if (table[index] == null) {
table[index] = entry;
size++;
} else {
Entry<K, V> curr = table[index];
while (curr != null) {
if (curr.key.equals(key)) {
curr.setValue(value);
return;
}
curr = curr.next;
}
entry.next = table[index].next;
table[index].next = entry;
size++;
}
}
// 从哈希表中获取某个键对应的值
public V get(K key) {
int index = hashFunc(key);
if (table[index] == null) {
return null;
} else {
Entry<K, V> curr = table[index];
while (curr != null) {
if (curr.key.equals(key)) {
return curr.getValue();
}
curr = curr.next;
}
return null;
}
}
// 从哈希表中移除某个键值对
public void remove(K key) {
int index = hashFunc(key);
if (table[index] == null) {
return;
} else {
Entry<K, V> curr = table[index];
Entry<K, V> prev = null;
while (curr != null) {
if (curr.key.equals(key)) {
if (prev == null) {
table[index] = curr.next;
} else {
prev.next = curr.next;
}
size--;
return;
}
prev = curr;
curr = curr.next;
}
}
}
// 获取哈希表的大小
public int size() {
return size;
}
// 判断哈希表是否为空
public boolean isEmpty() {
return size == 0;
}
}
这个实现中,我们使用了一个数组来存储哈希表的项,数组的大小为100。每当插入一个新的键值对时,我们使用哈希函数计算键的哈希值,并根据哈希值找到对应的数组索引。如果数组该索引位置没有元素,则直接插入;如果该索引位置已经有元素,则遍历链表,找到对应的键值对,并更新其值,如果链表中没有对应的键值对,则插入到链表的末尾。
通过这个简单的实现,我们可以利用哈希表实现快速插入、查找和删除操作,使得操作的时间复杂度达到常数级别。
