gpt4 book ai didi

Java 嵌套泛型类型不匹配

转载 作者:太空狗 更新时间:2023-10-29 22:53:43 24 4
gpt4 key购买 nike

在下面的例子中:

public static void main(String[] args) {

List<String> b = new ArrayList<String>();
first(b);
second(b);

List<List<String>> a = new ArrayList<List<String>>();
third(a);
fourth(a); // doesnt work

}

private static <T> void first(List<T> a){
System.out.println("List of T");
}

private static void second(List<?> a){
System.out.println("List of anything ");
}

private static <T> void third(List<List<T>> a){
System.out.println("List of a List of T ");
}

private static void fourth(List<List<?>> a){
System.out.println("List of a List of anything ");
}

为什么调用 second(b) 有效,但调用 fourth(a) 却无效

我收到以下错误:

The method fourth(List<List<?>>) in the type `TestTest` is not applicable for the arguments (`List<List<String>>`)

最佳答案

如果您希望能够调用fourthList<List<String>>参数,那么您需要将您的签名更改为:

private static void fourth(List<? extends List<?>> a){
System.out.println("List of a List of anything ");
}

上面的会起作用因为不像List<List<?>> , List<? extends List<?>>List<List<String>> 兼容.这样想:

List<List<String>> original = null;
List<? extends List<?>> ok = original; // This works
List<?> ok2 = original; // So does this
List<List<?>> notOk = original; // This doesn't

List<Integer> original = null;
List<? extends Number> ok = original; // This works
List<?> ok2 = original; // So does this
List<Number> notOk = original; // This doesn't

道理很简单。如果你有

private static void fourth(List<List<?>> a) {
List<?> ohOh = Arrays.asList(new Object());
a.add(ohOh);
}

然后如果您可以这样调用该方法:

List<List<String>> a = new ArrayList<List<String>>();
fourth(a);
String fail = a.get(0).get(0); // ClassCastException here!

关于Java 嵌套泛型类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13229979/

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