Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<List<?>> cannot be assigned to List<List<?>> when type parameter is involved

Tags:

java

generics

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?

like image 360
Feuermurmel Avatar asked Nov 14 '13 17:11

Feuermurmel


People also ask

Why ArrayList<Integer> cannot be assigned to list<child>?

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.

Is it possible to assign list type'list< widget>'to a widget?

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

Can the element type iterable<widget> be assigned to a list type?

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?

What is <List extends List<Integer> in Java?

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.


1 Answers

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();
}
like image 146
rgettman Avatar answered Sep 18 '22 21:09

rgettman