Java 嵌套泛型类型不匹配

2022-09-03 01:12:39

在以下示例中:

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>>`)

答案 1

如果您希望能够使用参数进行调用,则需要将签名更改为: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!

答案 2

A 不是 .List<List<String>>List<List<?>>

您应该能够将 any 放入 ,无论 .A 将只接受 .List<?>List<List<?>>?List<List<String>>List<String>


推荐