gpt4 book ai didi

java - 如何使 包含泛型类型参数?

转载 作者:搜寻专家 更新时间:2023-11-01 03:21:19 25 4
gpt4 key购买 nike

我有一个界面:

  /**
* Getter for any values within the GameObject and it's subclasses.
* Used as callback.
*
* Typical implementation would look like:
* new ValueGetter<SummonerSpell, String> {
* public String getValue(SummonerSpell source) {
* return source.toString();
* }
* }
* @param <T>
* @param <V> Type of value retrieved
*/
public static interface ValueGetter<T extends GameObject, V> {
public V getValue(T source);
}

在一种情况下,我想使用 GameObject 本身的接口(interface),而不是某些子类。我想在游戏对象的 List 中执行此操作:

  /**
* Will call the given value getter for all elements of this collection and return array of values.
* @param <T>
* @param <V>
* @param reader
* @return
*/
public <T extends GameObject, V> List<V> enumValues(ValueGetter<T, V> reader) {
List<V> vals = new ArrayList();

for(GameObject o : this) {
vals.add(reader.getValue(o));
}
return vals;
}

但是 reader.getValue(o) 导致编译错误:

incompatible types: GameObject cannot be converted to T
where T,V are type-variables:
T extends GameObject declared in method <T,V>enumValues(ValueGetter<T,V>)
V extends Object declared in method <T,V>enumValues(ValueGetter<T,V>)

我的问题如图:

image description

最佳答案

public <T extends GameObject, V> List<V> enumValues(List<T> list, ValueGetter<T, V> reader) {
List<V> vals = new ArrayList();

for(T o : list) {
vals.add(reader.getValue(o));
}
return vals;
}

关于java - 如何使 <T extends E> 包含泛型类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30003140/

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