简体   繁体   English

为什么以下Java代码导致编译错误

[英]Why is the following java code leads to compilation error

I am currently working on making my code contain more generics. 我目前正在努力使我的代码包含更多泛型。 I encountered a compilation error which looks quite complicated but which I was able to reduce to an equivalent error in the following code: 我遇到了一个看起来很复杂的编译错误,但是在以下代码中我可以将其减少到一个等效的错误:

List<List<?>> a = new ArrayList<List<Integer>>();

Why this happens? 为什么会这样? What can I do to fix it? 我该如何解决?

Instances of a generic class with different type parameters are not related, ie even though String is a subtype of Object , List<String> is not a subtype of List<Object> , and even though List<Integer> is a subtype of List<?> , List<List<Integer>> is not a subtype of List<List<?>> . 具有不同类型参数的泛型类的实例不相关,即,即使StringObject的子类型, List<String>不是List<Object>的子类型,并且即使List<Integer>List<?>的子类型。 List<?>List<List<Integer>>不是List<List<?>>的子类型。

Perhaps you are looking for 也许您正在寻找

List<? extends List<?>> a = new ArrayList<List<Integer>>();

The two sides have to match for the inner List : 两侧必须匹配内部List

List<List<?>> foo = new ArrayList<List<?>>();
foo.add(new ArrayList<Integer>());

Though this is rather silly as you've just defined a List of "Lists that can hold anything", and unless you know exactly what each is in that outer List, there's no way to divine it later due to type erasure. 尽管这很愚蠢,因为您刚刚定义了“可以容纳任何内容的列表”的列表,并且除非您确切地知道外部列表中的每个列表,否则以后由于类型擦除而无法对其进行区分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM