hashmap代码集合
时间: 2023-07-07 09:15:38 浏览: 39
好的,下面是一个简单的HashMap实现的代码示例:
```java
import java.util.LinkedList;
public class HashMap<K, V> {
private int capacity;
private LinkedList<Entry<K, V>>[] buckets;
public HashMap(int capacity) {
this.capacity = capacity;
this.buckets = new LinkedList[capacity];
}
private int hash(K key) {
return key.hashCode() % capacity;
}
public void put(K key, V value) {
int index = hash(key);
if (buckets[index] == null) {
buckets[index] = new LinkedList<Entry<K, V>>();
}
for (Entry<K, V> entry : buckets[index]) {
if (entry.key.equals(key)) {
entry.value = value;
return;
}
}
buckets[index].add(new Entry<K, V>(key, value));
}
public V get(K key) {
int index = hash(key);
if (buckets[index] == null) {
return null;
}
for (Entry<K, V> entry : buckets[index]) {
if (entry.key.equals(key)) {
return entry.value;
}
}
return null;
}
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中,我们使用一个LinkedList数组来存储键值对。当我们调用put()方法来添加一个新的键值对时,我们首先计算出键的哈希值,然后将其放入对应的链表中。如果链表中已经有了相同的键,我们就更新它的值。当我们调用get()方法来获取一个键的值时,我们首先计算出键的哈希值,然后在对应的链表中查找它。如果找到了,我们就返回它的值。如果没有找到,我们就返回null。
注意:这个HashMap是一个非线程安全的实现,如果需要使用在多线程环境中,请使用线程安全的HashMap实现。