Java哈希表的简单实现
时间: 2024-03-26 12:30:46 浏览: 24
以下是Java哈希表的简单实现:
```java
import java.util.LinkedList;
public class MyHashMap<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private LinkedList<Entry<K, V>>[] buckets;
private int size;
public MyHashMap() {
this(DEFAULT_CAPACITY);
}
public MyHashMap(int capacity) {
buckets = new LinkedList[capacity];
for (int i = 0; i < capacity; i++) {
buckets[i] = new LinkedList<>();
}
size = 0;
}
public void put(K key, V value) {
int index = getIndex(key);
LinkedList<Entry<K, V>> bucket = buckets[index];
for (Entry<K, V> entry : bucket) {
if (entry.key.equals(key)) {
entry.value = value;
return;
}
}
bucket.add(new Entry<>(key, value));
size++;
}
public V get(K key) {
int index = getIndex(key);
LinkedList<Entry<K, V>> bucket = buckets[index];
for (Entry<K, V> entry : bucket) {
if (entry.key.equals(key)) {
return entry.value;
}
}
return null;
}
public void remove(K key) {
int index = getIndex(key);
LinkedList<Entry<K, V>> bucket = buckets[index];
for (Entry<K, V> entry : bucket) {
if (entry.key.equals(key)) {
bucket.remove(entry);
size--;
return;
}
}
}
public boolean containsKey(K key) {
int index = getIndex(key);
LinkedList<Entry<K, V>> bucket = buckets[index];
for (Entry<K, V> entry : bucket) {
if (entry.key.equals(key)) {
return true;
}
}
return false;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
private int getIndex(K key) {
return Math.abs(key.hashCode()) % buckets.length;
}
private static class Entry<K, V> {
private K key;
private V value;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
}
}
```