public class MyHashMap<K,V> {
class Entry<K,V>{
private K k;
private V v;
private Entry<K,V> next;
Entry(K k, V v, Entry<K, V> next) {
this.k = k;
this.v = v;
this.next = next;
}
}
Entry<K,V> tables[];
private int CAPACITY=8;
private int size=0;
public MyHashMap(){
tables=new Entry[CAPACITY];
}
public Object put(K k,V v){
int hash = k.hashCode();
int i=hash%8;
for(Entry<K,V> entry=tables[i];entry!=null;entry=entry.next){
if(k==entry.k){
V oldValue= entry.v;
entry.v=v;
return oldValue;
}
}
addEntry(i,k,v);
return null;
}
private void addEntry(int i, K k, V v) {
Entry<K,V> entry =new Entry<>(k,v,tables[i]);
tables[i]=entry;
}
public Object get(K k){
int hash = k.hashCode();
int i=hash%8;
for(Entry<K,V> entry=tables[i];entry!=null;entry=entry.next){
if(k==entry.k){
return entry.v;
}
}
return null;
}
public static void main(String[] args) {
MyHashMap<String,String> hashMap = new MyHashMap<>();
hashMap.put("mao","g");
for (int i = 0; i < 10; i++) {
hashMap.put("mao"+i,"g"+i);
}
System.out.println(hashMap.get("mao"));
}
}
来源:oschina
链接:https://my.oschina.net/u/2511906/blog/3215771