hashmap写的代码啥样
时间: 2023-10-14 07:20:38 浏览: 23
HashMap 是一种基于哈希表实现的 Map 接口,它将键映射到值。下面是一个简单的 HashMap 实现:
```
public class HashMap<K, V> {
private Entry<K, V>[] buckets;
private static final int INITIAL_CAPACITY = 1 << 4; // 16
private int size = 0;
/**
* Entry 内部类,它封装了键值对。
*/
private static class Entry<K, V> {
final K key;
V value;
Entry<K, V> next;
Entry(K key, V value, Entry<K, V> next) {
this.key = key;
this.value = value;
this.next = next;
}
}
/**
* 构造函数,初始化 buckets 数组。
*/
public HashMap() {
this.buckets = new Entry[INITIAL_CAPACITY];
}
/**
* 根据键获取值。
*/
public V get(K key) {
int hash = key.hashCode() % buckets.length;
for (Entry<K, V> entry = buckets[hash]; entry != null; entry = entry.next) {
if (key.equals(entry.key)) {
return entry.value;
}
}
return null;
}
/**
* 将键值对存储到 HashMap 中。
*/
public void put(K key, V value) {
int hash = key.hashCode() % buckets.length;
for (Entry<K, V> entry = buckets[hash]; entry != null; entry = entry.next) {
if (key.equals(entry.key)) {
entry.value = value;
return;
}
}
Entry<K, V> newEntry = new Entry<K, V>(key, value, buckets[hash]);
buckets[hash] = newEntry;
size++;
}
/**
* 返回 HashMap 中键值对的数量。
*/
public int size() {
return size;
}
}
```
以上代码实现了基本的 HashMap 功能,包括存储键值对、获取值、获取大小等。需要注意的是,这只是一个简单的实现,实际的 HashMap 包含了更多的细节和优化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)