手写一个HashMap
根据JDK中HashMap的实现原理,手写一个类似的HashMap.
代码
public class MyHashMap <K, V> {
private int capacity;
private Node<K, V>[] table;
public MyHashMap () {
this.capacity = 16;
this.table = new Node[capacity];
}
public MyHashMap (int capacity) {
this.capacity = capacity;
this.table = new Node[capacity];
}
public void put(K key, V value) {
int hashCode = key.hashCode();
int index = hashCode % capacity;
Node<K, V> node = new Node<>(key, value);
if (table[index] == null) {
table[index] = node;
} else {
Node<K, V> cur = table[index];
while (cur.next != null) cur = cur.next;
cur.next = node;
}
}
public V get(K key) {
int hashCode = key.hashCode();
int index = hashCode % capacity;
Node<K, V> cur = table[index];
if (cur == null) return null;
else {
while (cur != null && !cur.key.equals(key)) cur = cur.next;
if (cur == null) return null;
else return cur.value;
}
}
public static void main(String[] args) {
MyHashMap<String, Integer> map = new MyHashMap<>(5);
map.put("key1", 100);
map.put("key2", 200);
map.put("key3", 300);
map.put("key4", 400);
map.put("key5", 500);
map.put("key6", 600);
int res1 = map.get("key1");
System.out.println(res1);
int res6 = map.get("key6");
System.out.println(res6);
}
static class Node <K, V> {
K key;
V value;
Node<K, V> next;
public Node(K key, V value) {
this.key = key;
this.value = value;
this.next = null;
}
}
}
测试结果