hashmap手写代码
时间: 2023-03-27 07:01:04 浏览: 114
java代码-使用java解决手写hashMap的源代码
好的,我可以回答这个问题。HashMap 是一种常用的数据结构,它可以用来存储键值对。以下是一个简单的手写 HashMap 代码示例:
```java
public class MyHashMap<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private static final float DEFAULT_LOAD_FACTOR = .75f;
private Entry<K, V>[] table;
private int size;
private int capacity;
private float loadFactor;
public MyHashMap() {
this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public MyHashMap(int capacity, float loadFactor) {
this.capacity = capacity;
this.loadFactor = loadFactor;
table = new Entry[capacity];
}
public void put(K key, V value) {
int index = hash(key);
Entry<K, V> entry = table[index];
while (entry != null) {
if (entry.key.equals(key)) {
entry.value = value;
return;
}
entry = entry.next;
}
Entry<K, V> newEntry = new Entry<>(key, value);
newEntry.next = table[index];
table[index] = newEntry;
size++;
if (size > capacity * loadFactor) {
resize();
}
}
public V get(K key) {
int index = hash(key);
Entry<K, V> entry = table[index];
while (entry != null) {
if (entry.key.equals(key)) {
return entry.value;
}
entry = entry.next;
}
return null;
}
public void remove(K key) {
int index = hash(key);
Entry<K, V> prev = null;
Entry<K, V> entry = table[index];
while (entry != null) {
if (entry.key.equals(key)) {
if (prev == null) {
table[index] = entry.next;
} else {
prev.next = entry.next;
}
size--;
return;
}
prev = entry;
entry = entry.next;
}
}
private int hash(K key) {
return key.hashCode() % capacity;
}
private void resize() {
capacity *= 2;
Entry<K, V>[] newTable = new Entry[capacity];
for (Entry<K, V> entry : table) {
while (entry != null) {
Entry<K, V> next = entry.next;
int index = hash(entry.key);
entry.next = newTable[index];
newTable[index] = entry;
entry = next;
}
}
table = newTable;
}
private static class Entry<K, V> {
K key;
V value;
Entry<K, V> next;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
}
}
```
这个 HashMap 实现了 put、get 和 remove 方法,它使用链表来解决哈希冲突,同时也支持动态扩容。
阅读全文