hashmap结构图如图所示:
由于红黑树实现的复杂性,本次就只实现一个链表+Entry table的hashmap
先定义接口:
/**
* @author xsj
* @create 2022-03-17 22:45
*/
public interface MyMap<K, V> {
V put(K key, V val);
V get(K key);
interface Entry<K, V> {
K getKey();
V getValue();
}
}
```java
public class MyHashMap<K, V> implements MyMap<K, V> {
private static final int DEFAULT_INITIAL_CAPACITY = 16;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private float loadFactor = 0;
private int initCapacity = 0;
private Entry<K, V>[] table = null;
public MyHashMap(int initCapacity, float loadFactor) {
this.initCapacity = initCapacity;
this.loadFactor = loadFactor;
table = new Entry[initCapacity];
}
@Override
public V put(K key, V val) {
int index = hash(key);
if (table[index] != null) {
Entry<K, V> e = table[index];
//用来保存e的前驱节点
Entry<K, V> e2 = null;
while (e != null) {
if (hash(e.key) == hash(key) && e.key.equals(hash(key))) {
e.value = val;
}
e2 = e;
e = e.next;
}
//如果不存在相同的key 则直接插入到尾节点的后面
e2.next = new Entry<>(key, val, null, index);
} else {
//如果table[index]为空 则直接插入
Entry<K, V> e = new Entry<>(key, val, null, index);
table[index] = e;
}
return val;
}
@Override
public V get(K key) {
// 根据key,计算下标index
int index = hash(key) % initCapacity;
Entry<K, V> e = table[index];
if (e == null) {
return null;
}
//遍历index处的链表找到key
while (e != null) {
// key== 或者 equals 因为泛型类 hash值==
if ((e.key == null && key == null) || hash(e.key) == hash(key) &&(e.key == key || e.key.equals(key))) {
return e.value;
}
e = e.next;
}
return e.value;
// return null;
}
private int hash(K key) {
int h;
return (key == null) ? 0 : Math.abs((h = key.hashCode())) ^ (h >>> 16);
}
class Entry<K, V> implements MyMap.Entry<K, V> {
K key;
V value;
Entry<K, V> next;
int index; // 记录下标
Entry(K key, V val, Entry<K, V> next, int index){
this.key = key;
this.value = val;
this.next = next;
this.index = index;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
}
}