In the following code, get()
is called and it's result assigned to a variable whose type is List<List<?>>
. get()
returns a List<List<T>>
and is called on an instance whose type parameter T
is set to ?
, so it should fit.
import java.util.List;
class Test {
void foo(NestedListProducer<?> test) {
List<List<?>> a = test.get();
}
interface NestedListProducer<T> {
List<List<T>> get();
}
}
But both IntelliJ IDEA and Oracle's javac
version 1.7.0_45 reject my code as invalid. This is the error message of 'javac':
java: incompatible types
required: java.util.List<java.util.List<?>>
found: java.util.List<java.util.List<capture#1 of ?>>
Why is this code invalid, i.e. what could go wrong if it was allowed?
In our example "base" type is List and "generic" type is Parent. So an ArrayList can be assigned to List but <Child> cannot be assigned to <Parent>. Base type is List so ArrayList can be assigned to it. But Generic type is List<Integer> and we are trying to pass object of subtype i.e. ArrayList<Integer>, so it will not work.
The element type 'List<widget>' can't be assigned to the list type 'Widget' androidiosflutter Share Improve this question Follow edited May 17 '18 at 13:29
The element type 'Iterable<Widget>' can't be assigned to the list type 'Widget' Hot Network Questions What is the rationale of banning proof-of-work instead of highly taxing it? Why did NATO not extend to include Ukraine along with the Baltic States back in 2004? How to debug an OrderItem in flow?
List<? extends List<Integer>> l= new ArrayList<ArrayList<Integer>> (); Here generic type "<? extends List<Integer>" says that this list reference can accept any object which is a subtype of List<Integer>, so it will accept object of its subtype "ArrayList<Integer>". Base type is List so ArrayList can be assigned to it.
The ?
is a wildcard meaning any type. One ?
cannot be the same as another ?
, because another ?
could be any other type, and they don't match. You must use generics to say that the types are the same:
// Make this generic
<A> void foo(NestedListProducer<A> test) {
List<List<A>> a = test.get();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With