Why is the following java code leads to compilation error

﹥>﹥吖頭↗ 提交于 2020-01-24 21:16:13

问题


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?


回答1:


Instances of a generic class with different type parameters are not related, i.e. 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<?>>.

Perhaps you are looking for

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



回答2:


The two sides have to match for the inner 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.



来源:https://stackoverflow.com/questions/9152302/why-is-the-following-java-code-leads-to-compilation-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!