Map.java
package HashMap;
public interface Map<K, V> {
void put(K key, V value);
V get(K key);
}
HashMap.java
package HashMap;
import java.util.LinkedList;
public class HashMap<K, V> implements Map<K, V> {
static class Node<K, V> {
final K key;
V value;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
private final LinkedList<Node<K, V>>[] tab = new LinkedList[8];
@Override
public void put(K key, V value) {
var idx = key.hashCode() & (tab.length - 1);
if (tab[idx] == null) {
tab[idx] = new LinkedList<>();
tab[idx].add(new Node<>(key, value));
} else {
tab[idx].add(new Node<>(key, value));
}
}
@Override
public V get(K key) {
var idx = key.hashCode() & (tab.length - 1);
for (var kvNode : tab[idx]) {
if (key.equals(kvNode.getKey())) {
return kvNode.getValue();
}
}
return null;
}
}
测试代码
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("01", "花花");
map.put("02", "豆豆");
System.out.println("碰撞前 key:" + "01" + ",value:" + map.get("01"));
map.put("09", "蛋蛋");
map.put("12", "苗苗");
System.out.println("碰撞前 key:" + "01" + ",value:" + map.get("01"));
}