编写一个hashmap
时间: 2023-05-15 14:05:51 浏览: 52
好的,下面是一个简单的HashMap的实现:
```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;
private int threshold;
private float loadFactor;
public MyHashMap() {
this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public MyHashMap(int initialCapacity, float loadFactor) {
if (initialCapacity <= 0) {
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
}
if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
}
this.loadFactor = loadFactor;
this.table = new Entry[initialCapacity];
this.threshold = (int) (initialCapacity * loadFactor);
}
public void put(K key, V value) {
int hash = hash(key);
int index = indexFor(hash, table.length);
for (Entry<K, V> e = table[index]; e != null; e = e.next) {
if (e.hash == hash && (e.key == key || e.key.equals(key))) {
e.value = value;
return;
}
}
addEntry(hash, key, value, index);
}
public V get(K key) {
int hash = hash(key);
int index = indexFor(hash, table.length);
for (Entry<K, V> e = table[index]; e != null; e = e.next) {
if (e.hash == hash && (e.key == key || e.key.equals(key))) {
return e.value;
}
}
return null;
}
private void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K, V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
if (size++ >= threshold) {
resize(2 * table.length);
}
}
private void resize(int newCapacity) {
Entry<K, V>[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == Integer.MAX_VALUE) {
threshold = Integer.MAX_VALUE;
return;
}
Entry<K, V>[] newTable = new Entry[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int) (newCapacity * loadFactor);
}
private void transfer(Entry<K, V>[] newTable) {
Entry<K, V>[] src = table;
int newCapacity = newTable.length;
for (int j = 0; j < src.length; j++) {
Entry<K, V> e = src[j];
if (e != null) {
src[j] = null;
do {
Entry<K, V> next = e.next;
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
} while (e != null);
}
}
}
private int hash(K key) {
return key.hashCode();
}
private int indexFor(int hash, int length) {
return hash & (length - 1);
}
static class Entry<K, V> {
final int hash;
final K key;
V value;
Entry<K, V> next;
Entry(int hash, K key, V value, Entry<K, V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
}
```
这是一个基于拉链法的HashMap实现,使用了泛型,支持任意类型的键值对。