hashmap实现代码
时间: 2023-07-07 17:08:51 浏览: 39
下面是一个简单的 HashMap 的实现示例代码:
```java
public class MyHashMap<K, V> {
private int size;
private final int DEFAULT_CAPACITY = 16;
private Entry<K, V>[] table;
public MyHashMap() {
table = new Entry[DEFAULT_CAPACITY];
}
public void put(K key, V value) {
if (key == null) {
return;
}
int hash = key.hashCode();
int index = hash % DEFAULT_CAPACITY;
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++;
}
public V get(K key) {
if (key == null) {
return null;
}
int hash = key.hashCode();
int index = hash % DEFAULT_CAPACITY;
Entry<K, V> entry = table[index];
while (entry != null) {
if (entry.key.equals(key)) {
return entry.value;
}
entry = entry.next;
}
return null;
}
public boolean containsKey(K key) {
if (key == null) {
return false;
}
int hash = key.hashCode();
int index = hash % DEFAULT_CAPACITY;
Entry<K, V> entry = table[index];
while (entry != null) {
if (entry.key.equals(key)) {
return true;
}
entry = entry.next;
}
return false;
}
public boolean remove(K key) {
if (key == null) {
return false;
}
int hash = key.hashCode();
int index = hash % DEFAULT_CAPACITY;
Entry<K, V> entry = table[index];
Entry<K, V> prev = null;
while (entry != null) {
if (entry.key.equals(key)) {
if (prev == null) {
table[index] = entry.next;
} else {
prev.next = entry.next;
}
size--;
return true;
}
prev = entry;
entry = entry.next;
}
return false;
}
public int size() {
return size;
}
private class Entry<K, V> {
private final K key;
private V value;
private Entry<K, V> next;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
}
}
```
在这个实现中,我们使用了一个数组来存储键值对,每个键值对被封装成一个 `Entry` 对象,并且使用链表法来解决哈希冲突。`put` 方法将键值对添加到哈希表中,`get` 方法通过键获取对应的值,`containsKey` 方法检查哈希表中是否含有指定的键,`remove` 方法从哈希表中移除指定的键值对,`size` 方法返回哈希表中键值对的数量。