简体   繁体   中英

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<?>> .

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<?>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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