gpt4 book ai didi

Java 设置 ArrayList 中对象的通用值

转载 作者:行者123 更新时间:2023-12-02 11:48:56 25 4
gpt4 key购买 nike

我有课

 public class ValueObject<T> {
private T value;

public void setValue(T value){
this.value = value
}
}

在另一个类中,我有一个来自第一个类的对象数组

ArrayList<ValueObject<?>> valueObjects = new ArrayList<>();
ArrayList<String> valueNames = new ArrayList<>();

现在我想编写一个方法,它在第二个数组中查找名称,并将新值分配给该 arrayList 中第一个对象的实例

ValueObject<?> get(String name) {
return valueObjects.get(valueNames.indexOf(name));
}

public <T> void set(String name, T value) {
get(name).setValue(value);
}

但我无法让它发挥作用。我需要用 写东西吗?在 set() 方法中?

谢谢

最佳答案

您没有提供完整的示例,因此不确定哪个会对您有帮助。

版本 1(如果您可以使用 List<ValueObject<T>>)因为所有ValueObjects保持相同的类型。

static class Lookup<T2> {

List<ValueObject<T2>> valueObjects = new ArrayList<>();
List<String> valueNames = new ArrayList<>();

ValueObject<T2> get(String name) {
return valueObjects.get(valueNames.indexOf(name));
}

public void set(String name, T2 value) {
get(name).setValue(value);
}
}

版本 2 if valueObjects确实包含ValueObject具有不同的包含类:

@SuppressWarnings("unchecked")
static class Lookup2 {

List<ValueObject<?>> valueObjects = new ArrayList<>();
List<String> valueNames = new ArrayList<>();

/* unsafe get */
ValueObject<?> get(String name) {
return valueObjects.get(valueNames.indexOf(name));
}


/* set using unsafe get */
public <T> void setUnsafe(String name, T value) {
/* might add handling of runtime exceptions */
((ValueObject<T>)get(name)).setValue(value);
}

/* safe get when client knows class */
<T> ValueObject<T> get(String name, Class<T> clazz) {
/* might do instanceOf check here to throw custom exception */
return (ValueObject<T>) valueObjects.get(valueNames.indexOf(name));
}

/* set using safe get */
public <T> void set(String name, T value) {
/* might add handling of runtime exceptions */
get(name, (Class<T>) value.getClass()).setValue(value);
}
}

关于Java 设置 ArrayList 中对象的通用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48014264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com