Wednesday, August 13, 2014

实现hashmap

若是thread-safe,用synchronized就ok了
class Entry<K, V>{
    private final K key;
    private V value;
    Entry<K,V> next;
    
    Entry(K k, V v){
        key = k;
        value = v;
    }
    public K getKey(){
        return key;
    }
    public V getValue(){
        return value;
    }
    public V setValue(V v){
        V old = value;
        value = v;
        return old;
    }
    public boolean equals(Object o){
        if(!(o instanceof Entry))
                return false;
        Entry<K,V> e = (Entry<K,V>) o;
        return (this.getKey()==null ? e.getKey()==null : this.getKey().equals(e.getKey())) && (this.getValue()==null ? e.getValue()==null : e.getValue().equals(e.getValue()));  
    }
    public final int hashCode() {
        return (key==null ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode());
    }
}


class HashMap<K, V>{
    private static final int size = 16;
    private Entry[] table ;
    
    public HashMap(){
        table = new Entry[size];
    }
 
    public int getIndex(int hashcode, int length){
        return hashcode % length;
    }
    
    public V get(K k){
        int i = getIndex(k.hashCode(), size);
        Entry<K, V> e = table[i];
        while(e!=null){
            if(e.getKey().equals(k))
                return e.getValue();
            e = e.next;
        }
        return null;
    }
    
    public V put(K k, V v){
        int i = getIndex(k.hashCode(), size);
        Entry<K, V> e = table[i];
        if(e!=null){
            if(e.getKey().equals(k)){
                V old = e.getValue();
                e.setValue(v);
                return old;
            }else{
                while(e.next!=null)
                    e = e.next;
                Entry<K, V> newEntry = new Entry<K, V>(k, v);
                e.next = newEntry;
            }
        }else{
            table[i] = new Entry<K,V>(k,v);
        }
        return null;
    }
}

No comments:

Post a Comment