キー値のペアを格納するJavaデータ型を持ち、キーまたはインデックスのいずれかによって値を取得できるようにしたいとします。キーまたはインデックスのいずれかを使用して、Javaのデータ型から値を取得します。
java.util.Dictionary
に拡張された独自のデータ型が転記され、インデックスで取り出す機能を実現するためにat
関数が用意されています。
class DataHash <K,V> extends Dictionary<K,V> {
private List<K> keyOrder = new ArrayList<K>();
private Dictionary<K,V> internalDataStore = new Hashtable<K,V>();
@Override
public V put(K key, V value){
//guards go here to prevent null, duplicate keys etc.
this.keyOrder.add(key);
return this.internalDataStore.put(key, value);
}
@Override
public V get(K key){
return this.internalDataStore.get(key);
}
public V at(int index){
K key = this.keyOrder.get(index);
return this.internalDataStore.get(key);
}
//and other functions to extend dictionary etc.
//all keeping the keyOrder in sync with the internalDataStore
}
SOのための私の質問はこれを行い、既存のデータ型、または私のカスタムデータ型でこれを実装するためのより効率的な方法があるかどうかでしょうか?