HashMap的put get最简单实现

人走茶凉 提交于 2020-04-06 05:54:51

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"));
}

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!