promotion image of download ymail app
Promoted

有關JAVA DataStructure 資料結構問題

如何實作map ADT 使用 (1) hash table (2) list

用文字"簡述"就可以了

感激不盡~!!

1 Answer

Rating
  • 8 years ago
    Favorite Answer

    請參考我的做法

    import java.util.*;

    interface IMyMap<K,V> {

    // querying whether a map contains a given key

    public boolean containsKey(Object key);

    // lookup of a value associated with a given key, if the key is present

    public V get(Object key);

    // inserting a key and a value to be associated with it, if the key is not

    // already present

    public V put(K key, V value);

    // removing a key (together with the associated value), if the key is present

    public V remove(Object key);

    }

    class MyMap3<K,V> implements IMyMap<K,V> {

    private Hashtable<K, V> map;

    public MyMap3() { map = new Hashtable<K, V>(); }

    public boolean containsKey(Object key) { return map.containsKey(key); }

    public V get(Object key) { return map.get(key); }

    public V put(K key, V value) { return map.put(key, value); }

    public V remove(Object key) { return map.remove(key); }

    }

    class MyMap4<K,V> implements IMyMap<K,V> {

    private List<K> keys;

    private List<V> values;

    public MyMap4() {

    keys = new ArrayList<K>();

    values = new ArrayList<V>();

    }

    public boolean containsKey(Object key) {

    return keys.contains(key);

    }

    public V get(Object key) {

    int idx = keys.indexOf(key);

    if (idx < 0) return null;

    return values.get(idx);

    }

    public V put(K key, V value) {

    V v2 = get(key);

    if (v2 == null) {

    int lastIdx = keys.size();

    keys.add(lastIdx, key);

    values.add(lastIdx, value);

    } else {

    int idx = keys.indexOf(key);

    values.set(idx, value);

    }

    return v2;

    }

    public V remove(Object key) {

    V v2 = get(key);

    if (v2 != null) {

    int idx = keys.indexOf(key);

    keys.remove(idx);

    values.remove(idx);

    }

    return v2;

    }

    }

    因字數限制,測試部分程式碼請見 http://pastie.org/5665924

    參考資料

    ADT: Map

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.