gpt4 book ai didi

带有通配符的 Java 泛型无法编译

转载 作者:行者123 更新时间:2023-12-01 19:21:08 25 4
gpt4 key购买 nike

我无法理解带有通配符的 Java 泛型的细节。具体来说,为什么它不能编译。

public class Test {

abstract class Function<A, B> {
abstract B call(A a);
}

interface PropertyType {
String bubbles();
}

class Apartment implements PropertyType {
@Override
public String bubbles() {
return "bubbles";
}
}

public void invokeFunctionOnAList() {
List<Apartment> apts = new ArrayList<Apartment>();
functionLoop(apts, new Function<Apartment, String>() {

@Override
String call(Apartment a) {
return a.bubbles();
}
});
}

public void functionLoop(List<? extends PropertyType> list, Function<? extends PropertyType, String> t) {
for (PropertyType p : list) {
t.call(p);
}
}
}

最佳答案

实际放置该代码的最正式正确的方法是

public <C extends PropertyType> void functionLoop(
List<C> list, Function<? super C, String> t) {
for (C p : list) {
t.call(p);
}
}

我发现的关于泛型的最好解释是 Joshua Bloch 的“Effective Java”。您可以在 presentation 中找到与您的示例相关的一小段摘录。 .

关于带有通配符的 Java 泛型无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4193733/

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