上篇博客讲了HashMap的底层原理,此处附上连接:HashMap的底层原理,下来以后自己实现了一个HashMap,以HashMap的get()和put()为主。
代码如下:
class Entry<K,V> {
K key;
V value;
Entry<K,V> next=null;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
public interface Map<K,V> {
V get(K key);
V put(K key,V value);
}
public class HashMap<K,V>implements Map<K,V> {
//要求table.length 必须是2的幂次方
private Entry<K,V>[]table=new Entry[16];
//HashMap中已经保存的有效key的个数
private int size=0;
private static final double LOADER_FACTOR_THRESHOLD=0.75;
@Override
public V get(K key) {
//1.根据key得到下标
int index;
if(key==null){