Java 手写 HashMap 实现示例
以下是 Java 手写 HashMap 的示例代码:
public class MyHashMap<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private Node<K, V>[] buckets;
private int size;
public MyHashMap() {
this(DEFAULT_CAPACITY);
}
public MyHashMap(int capacity) {
buckets = new Node[capacity];
}
public void put(K key, V value) {
int index = getIndex(key);
Node<K, V> node = buckets[index];
while (node != null) {
if (node.key.equals(key)) {
node.value = value;
return;
}
node = node.next;
}
Node<K, V> newNode = new Node<>(key, value);
newNode.next = buckets[index];
buckets[index] = newNode;
size++;
if (size > buckets.length * DEFAULT_LOAD_FACTOR) {
resize();
}
}
public V get(K key) {
int index = getIndex(key);
Node<K, V> node = buckets[index];
while (node != null) {
if (node.key.equals(key)) {
return node.value;
}
node = node.next;
}
return null;
}
public void remove(K key) {
int index = getIndex(key);
Node<K, V> node = buckets[index];
Node<K, V> prev = null;
while (node != null) {
if (node.key.equals(key)) {
if (prev == null) {
buckets[index] = node.next;
} else {
prev.next = node.next;
}
size--;
return;
}
prev = node;
node = node.next;
}
}
public int size() {
return size;
}
private int getIndex(K key) {
return key == null ? 0 : Math.abs(key.hashCode() % buckets.length);
}
private void resize() {
Node<K, V>[] oldBuckets = buckets;
buckets = new Node[oldBuckets.length * 2];
size = 0;
for (Node<K, V> node : oldBuckets) {
while (node != null) {
put(node.key, node.value);
node = node.next;
}
}
}
private static class Node<K, V> {
K key;
V value;
Node<K, V> next;
Node(K key, V value) {
this.key = key;
this.value = value;
}
}
}
此代码实现了一个简单的 HashMap,其中:
- 'buckets' 是一个存储节点的数组,每个节点包含一个键值对和一个指向下一个节点的指针。
- 'size' 表示 HashMap 的大小。
- 'put' 方法将键值对插入 HashMap 中。如果已经存在相同的键,则覆盖旧值。如果 HashMap 的负载因子超过了默认值 0.75,则对数组进行调整。
- 'get' 方法检索键对应的值。如果键不存在,则返回 null。
- 'remove' 方法删除键值对。如果键不存在,则不执行任何操作。
- 'size' 方法返回 HashMap 的大小。
- 'getIndex' 方法根据键的哈希码计算存储桶的索引。
- 'resize' 方法对数组进行调整,以支持更多的键值对。
- 'Node' 类表示一个存储在 HashMap 中的节点。每个节点包含一个键值对和一个指向下一个节点的指针。
请注意,此代码中的实现仅用于示例目的。实际的 HashMap 实现可能包含更多的特性和优化。
原文地址: http://www.cveoy.top/t/topic/mOJA 著作权归作者所有。请勿转载和采集!