问题
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