本例子实现了Java数组+链表实现HashMap,可往HashMap中存null值。
public class MyHashMap<K,V> {
//定义一个数组
private Entry<K,V>[] entries=new Entry[1000];
class Entry<K,V>{
K k;
V v;
Entry next;
public Entry(K k, V v) {
this.k = k;
this.v = v;
}
}
public void put(K k,V v){
//计算出存放在数组中的位置,k为null则直接存放在index=0位置
int index = k==null ? 0: k.hashCode()%entries.length;
// System.out.println(index);
//若数组中此时无值,则可直接存入
if(entries[index]==null){
entries[index]=new Entry<>(k,v);
}else {
//发生了hash冲突
entries[index].next=new Entry(k,v);
}
}
public V get(K k){
int index = k==null ? 0: k.hashCode()%entries.length;
while (entries[index]!=null){
//这一步很重要
if(entries[index].k==null||entries[index].k.equals(k)){
return entries[index].v;
}
entries[index]=entries[index].next;
}
return null;
}
public static void main(String[] args) {
MyHashMap<Object,Object> myHashMap=new MyHashMap<>();
myHashMap.put("a","cc");
System.out.println(myHashMap.get("a"));
myHashMap.put(97,"dd");
System.out.println(myHashMap.get(97));
myHashMap.put(null,"ee");
System.out.println(myHashMap.get(null));
}
}