使用拉链法实现的简单哈希表,用于加深对于Java的使用和数据结构的理解
代码的put函数有个小bug,为了简单实现直接用的头插法添加元素,但是大部分情况下应该检测是否已经含有了这个元素并更新
Java中的泛型使用擦除法实现的,简单来说就是把类型都转换成Object
这也是为什么泛型不支持基础类型的原因,因为基础类型无法转换成Object
package cn.nya.hash;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* Program: first - SimpleHashMap
* Description: 简单HashMap
* Author: Nya
* CreateAt: 2024-03-04 12:01
**/
public class SimpleHashMap<K, V> {
private static final int DEFAULT_CAPACITY = 1 << 4;
private class SimpleHashPair {
private K key;
private V value;
private SimpleHashPair next;
private int retrievalCount;
public SimpleHashPair(K key, V value, SimpleHashPair next) {
this.key = key;
this.value = value;
this.next = next;
this.retrievalCount = 0;
}
public SimpleHashPair(K key, V value) {
this.key = key;
this.value = value;
this.next = null;
this.retrievalCount = 0;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public int getRetrievalCount() {
return retrievalCount;
}
public void setRetrievalCount(int retrievalCount) {
this.retrievalCount = retrievalCount;
}
public SimpleHashPair getNext() {
return next;
}
public void setNext(SimpleHashPair next) {
this.next = next;
}
}
// 索引表
private ArrayList<SimpleHashPair> indexArray;
public SimpleHashMap() {
initializeIndexArray(DEFAULT_CAPACITY);
}
public SimpleHashMap(int size) {
initializeIndexArray(size);
}
private void initializeIndexArray(int capacity) {
indexArray = new ArrayList<>(capacity);
for (int i = 0; i < capacity; i++) {
indexArray.add(null);
}
}
private int capacity() {
return indexArray.size();
}
private int getHashCode(K key) {
int hashCode = key.hashCode();
return hashCode % capacity();
}
/**
* 判断是否含有key
*
* @param key 需要查找的key
* @return 是否包含
*/
public boolean containsKey(K key) {
return get(key) != null;
}
/**
* 哈希表加入元素
*
* @param key 键
* @param value 值
*/
public void put(K key, V value) {
int index = getHashCode(key);
SimpleHashPair newPair = new SimpleHashPair(key, value);
SimpleHashPair head = indexArray.get(index);
if (head == null) {
indexArray.set(index, newPair);
return;
}
// 在这里可以遍历链表,寻找是否有需要添加的key,如果有就更新,否则新增
SimpleHashPair next = head.next;
head.setNext(newPair.getNext());
newPair.setNext(next);
}
/**
* 获取哈希表值
*
* @param key 键
* @return 值
*/
public V get(K key) {
int index = getHashCode(key);
SimpleHashPair head = indexArray.get(index);
if (head == null) {
return null;
}
while (head != null && !head.getKey().equals(key)) {
head = head.next;
}
if (head != null) {
return head.getValue();
}
return null;
}
}