每次我认为自己更好地理解泛型(并可以在不编译的情况下回答问题)时,我都会遇到一个打破这个理论的例子。以下是一个非常简单的例子:
static void consumer(List<? super List<String>> param) {
System.out.println(param);
}
两种调用方法:
public static void main(String[] args) {
List<String> list = List.of("123");
consumer(list);
consumer(List.of("123"));
}
对我来说,这些调用中没有一个应该编译通过。
String
不是 List
的超类型。然而,第二个调用编译通过了。但是假设这是因为编译器可以推断出某种类型,那么它会在运行时失败,对吗?对吗?不对。它能正常工作。有没有人能给我的生活带来一点理智?
List<List<? super String>>
,你写的是List<? super List<String>>
。 - chrylis -cautiouslyoptimistic-List.of
的泛型参数推断为Object
...(不确定实际情况是否如此)。 - SweeperX extends String implements List
的?编译器只需要找到一个满足super List<String>
并且可以从String
转换的类型(即String
的超类),而Object
满足这个条件。为什么要使用X extends String implements List
? - Sweeper--debug=verboseResolution=all
(有时很有帮助) 选项... - Eugene