请建立一个hashmap容器
时间: 2023-09-16 09:07:37 浏览: 43
好的,以下是一个简单的HashMap容器的实现:
```java
import java.util.ArrayList;
public class MyHashMap<K, V> {
private int capacity;
private ArrayList<Entry<K, V>>[] buckets;
public MyHashMap(int capacity) {
this.capacity = capacity;
this.buckets = new ArrayList[capacity];
for (int i = 0; i < capacity; i++) {
buckets[i] = new ArrayList<>();
}
}
public void put(K key, V value) {
int index = getIndex(key);
ArrayList<Entry<K, V>> bucket = buckets[index];
for (Entry<K, V> entry : bucket) {
if (entry.key.equals(key)) {
entry.value = value;
return;
}
}
bucket.add(new Entry<>(key, value));
}
public V get(K key) {
int index = getIndex(key);
ArrayList<Entry<K, V>> bucket = buckets[index];
for (Entry<K, V> entry : bucket) {
if (entry.key.equals(key)) {
return entry.value;
}
}
return null;
}
private int getIndex(K key) {
return Math.abs(key.hashCode() % capacity);
}
private static class Entry<K, V> {
private K key;
private V value;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
}
}
```
这个HashMap容器使用了ArrayList作为桶,每个桶存储一个键值对的链表。当需要插入或查找键值对时,先根据键的hashCode值计算桶的索引,然后在对应的链表中查找或插入键值对。如果多个键的hashCode值相同,它们会被存储在同一个桶中,因此需要使用equals方法进行比较。