手写hashmap
时间: 2023-07-07 12:08:55 浏览: 101
java代码-使用java解决手写hashMap的源代码
好的,这里是一个简单的手写hashmap的实现:
```java
public class MyHashMap<K, V> {
private int size;
private int capacity;
private Node<K, V>[] table;
private static class Node<K, V> {
final K key;
V value;
Node<K, V> next;
Node(K key, V value, Node<K, V> next) {
this.key = key;
this.value = value;
this.next = next;
}
}
public MyHashMap(int capacity) {
this.size = 0;
this.capacity = capacity;
this.table = new Node[capacity];
}
public V get(K key) {
int index = hash(key);
Node<K, V> node = table[index];
while (node != null) {
if (node.key.equals(key)) {
return node.value;
}
node = node.next;
}
return null;
}
public void put(K key, V value) {
int index = hash(key);
Node<K, V> node = table[index];
while (node != null) {
if (node.key.equals(key)) {
node.value = value;
return;
}
node = node.next;
}
// If the key does not exist in the map, add a new node to the front of the list at the index.
Node<K, V> newNode = new Node<>(key, value, table[index]);
table[index] = newNode;
size++;
// If the map has exceeded its load factor, resize the table.
if (size > capacity * 0.75) {
resize();
}
}
public void remove(K key) {
int index = hash(key);
Node<K, V> node = table[index];
Node<K, V> prev = null;
while (node != null) {
if (node.key.equals(key)) {
if (prev == null) {
table[index] = node.next;
} else {
prev.next = node.next;
}
size--;
return;
}
prev = node;
node = node.next;
}
}
private int hash(K key) {
return key.hashCode() % capacity;
}
private void resize() {
capacity *= 2;
Node<K, V>[] newTable = new Node[capacity];
for (Node<K, V> node : table) {
while (node != null) {
Node<K, V> next = node.next;
int index = hash(node.key);
node.next = newTable[index];
newTable[index] = node;
node = next;
}
}
table = newTable;
}
}
```
这个HashMap使用链表来解决冲突,并且在size超过capacity*0.75时会自动扩容。
阅读全文