hashMap 手写 java
时间: 2023-09-13 11:13:45 浏览: 49
好的,以下是一个简单的手写 HashMap 的 Java 实现:
```java
public class MyHashMap<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private Entry<K, V>[] table;
private int size;
public MyHashMap() {
this.table = new Entry[DEFAULT_CAPACITY];
this.size = 0;
}
public void put(K key, V value) {
if (key == null) {
throw new IllegalArgumentException("Key cannot be null");
}
int hash = hash(key);
int index = index(hash);
for (Entry<K, V> entry = table[index]; entry != null; entry = entry.next) {
if (entry.hash == hash && entry.key.equals(key)) {
entry.value = value;
return;
}
}
addEntry(key, value, hash, index);
}
public V get(K key) {
if (key == null) {
throw new IllegalArgumentException("Key cannot be null");
}
int hash = hash(key);
int index = index(hash);
for (Entry<K, V> entry = table[index]; entry != null; entry = entry.next) {
if (entry.hash == hash && entry.key.equals(key)) {
return entry.value;
}
}
return null;
}
public void remove(K key) {
if (key == null) {
throw new IllegalArgumentException("Key cannot be null");
}
int hash = hash(key);
int index = index(hash);
Entry<K, V> prev = null;
Entry<K, V> entry = table[index];
while (entry != null) {
if (entry.hash == hash && entry.key.equals(key)) {
if (prev == null) {
table[index] = entry.next;
} else {
prev.next = entry.next;
}
size--;
return;
}
prev = entry;
entry = entry.next;
}
}
public int size() {
return size;
}
private int hash(K key) {
return key.hashCode();
}
private int index(int hash) {
return hash & (table.length - 1);
}
private void addEntry(K key, V value, int hash, int index) {
Entry<K, V> entry = table[index];
table[index] = new Entry<>(key, value, hash, entry);
size++;
if (size > table.length * DEFAULT_LOAD_FACTOR) {
resize();
}
}
private void resize() {
int newCapacity = table.length * 2;
Entry<K, V>[] newTable = new Entry[newCapacity];
for (Entry<K, V> entry : table) {
while (entry != null) {
int index = index(entry.hash);
Entry<K, V> next = entry.next;
entry.next = newTable[index];
newTable[index] = entry;
entry = next;
}
}
table = newTable;
}
private static class Entry<K, V> {
final K key;
V value;
final int hash;
Entry<K, V> next;
Entry(K key, V value, int hash, Entry<K, V> next) {
this.key = key;
this.value = value;
this.hash = hash;
this.next = next;
}
}
}
```
这个 HashMap 使用了拉链法解决哈希冲突,并且支持动态调整容量。