Java にオブジェクト (Double など) があり、それぞれの要素がその Double への参照である長さ n のリストが必要です。これを行うためのイディオムが欲しいのですが、O(1) のみのメモリを使用する必要はありません。
3 に答える
1
この目的のためにデータ構造を作成するのはどうですか? そんな感じ:
import java.util.HashMap;
public class SpecialArray {
private HashMap<Integer, Double> elements;
private Double specialElement;
private int size;
public SpecialArray(Double specialElement, int size) {
this.elements = new HashMap<Integer, Double>();
this.specialElement = specialElement;
this.size = size;
}
public Double get(int index) {
if(index<0 || index>=size) {
return null;
}
if(elements.containsKey(index)) {
return elements.get(index);
}
return specialElement;
}
public boolean add(Double d, int index) {
if(index<0 || index>=size || elements.containsKey(index)) {
return false;
}
elements.put(index, d);
return true;
}
}
もちろん、これは完全な例ではなく、ジェネリック型で記述できます。しかし、リストに他の要素がいくつかある場合、これは役立つと思います。
于 2013-02-19T09:29:05.937 に答える
1
于 2013-02-19T09:21:19.893 に答える
0
Collections.fill()
あなたを助けるかもしれません
于 2013-02-19T09:14:24.477 に答える