Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Object to Generic List with two types

Tags:

java

generics

I read a couple of posts such as here but I was unable to find the solution for my problem.

Why I am unable to add d? It is a subtype of Object... Type of d: A<B<X>>

 List<A<B<? extends Object>>> rv=new LinkedList<>();
 rv.add(d); //not working

EDIT

I tried to simplify the problem. When I do:

 A<B<?>> abcv=new A<B<String>>();

I get the error: Type mismatch: cannot convert from A<B<String>> to A<B<?>>

However, String is compatible with "?" - so why is it not working? I want to add elements to a list where the last type can by anything, something like this:

List<A<B<?>>> rv=new LinkedList<>();
rv.add(new A<B<X>>());
rv.add(new A<B<String>>());
rv.add(new A<B<Integer>>());
like image 491
user3579222 Avatar asked Jan 02 '19 09:01

user3579222


1 Answers

List<SubClaz> is not a subtype of List<SuperClaz> in Java. That's why the wildcards are used: List<SubClaz> is a subtype of List<? extends SuperClaz>.

Now for your A<B<?>> abcv=new A<B<String>>(); example:

By adding the wildcard, you're making B<String> a subtype of B<?>, but since these are also wrapped by another type A, we're back to the first problem:
A<B<String>> is not a subtype of A<B<?>>
(Notice B<?> is the SuperClaz and B<String> is the SubClaz in this case).

You can fix this the same way; by adding another wildcard:
A<B<String>>() is a subtype of A<? extends B<?>>.

Keep in mind that this doesn't allow you to read or manipulate the list as you want. Search for covariance and contravariance for more detail. Here is a good one: http://bayou.io/draft/Capturing_Wildcards.html

like image 187
oskansavli Avatar answered Oct 13 '22 23:10

oskansavli