-3

エントリのリストを作成しようとしていますが、これを行う方法に問題があります。可能かどうかはわかりませんが、Example オブジェクトが見つけたエントリの V を返すようにしようとしています。「オブジェクト」だけを返したくありません。はい、get() メソッドでコンパイル エラーが発生しますが、動作するように修正するにはどうすればよいですか? ありがとう。各エントリには異なるタイプがあります。

public class Example {

private List<Entry<?>> data = new ArrayList<Entry<?>>();

public Example() {

}

public V get(String path) {
    for (Entry<?> entry : data) {
        if (entry.getPath().equals(path)) {
            return entry.getValue();
        }
    }
    return null;
}

private static class Entry<V> {

    private String path;
    private V value;

    public Entry() {

    }

    public Entry(String path, V value) {
        this.path = path;
        this.value = value;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void setValue(V value) {
        this.value = value;
    }

    private String getPath() {
        return path;
    }

    private V getValue() {
        return value;
    }

}

}

4

2 に答える 2

2

ジェネリックにしたくないかもしれませんが、ジェネリックオブジェクトExampleを保存してジェネリックEntryオブジェクトをget(String)返す必要があるため、それが必要です。

public class Example<T> {

    private List<Entry<T>> data = new ArrayList<Entry<T>>();

    public Example() {

    }

    public T get(String path) {
        for (Entry<T> entry : data) {
            if (entry.getPath().equals(path)) {
                return entry.getValue();
            }
        }
        return null;
    }

    private static class Entry<V> {
        . . .
    }
}
于 2013-07-21T08:40:55.023 に答える
0

V呼び出し時の型がわかっている場合はget(String)、パラメーターを追加して、コンテンツを必要な型Classにキャストできます。Entry<?>

public <V> V get(String path, Class<V> clazz) {
    for (Entry<?> entry : data) {
        if (entry.getPath().equals(path) && clazz.isInstance(entry.getValue())) {
            return clazz.cast(entry.getValue());
        }
    }
    return null;
}

そして、これを使用する方法は次のとおりです。

example.add(new Entry<String>("color", "blue"));
example.add(new Entry<String>("model", "Some Model"));
example.add(new Entry<Integer>("numberOfTires", 4));

Integer tires = example.get("age", Integer.class);
String model = example.get("model", String.class);

ところで、Mapパスのリストを反復する代わりに a を使用する必要があるかもしれません。

于 2013-07-21T08:57:51.217 に答える