Assigning a variable from nested generics in generic class in Java?

73 Views Asked by At

If I have the following code:

public class DummyClass<T> {
    public List<T> getList() {
        return new ArrayList<T>();
    }
    public Set<List<T>> getListSet() {
        return new HashSet<List<T>>();
    }
}

and I have a DummyClass<?> dummy,

I can do

List<?> list = dummy.getList();

without any errors.

However,

Set<List<?>> listSet = dummy.getListSet();

gives the compile error:

Type mismatch: cannot convert from Set<List<capture#1-of ?>> to Set<List<?>>

for the line assigning dummy.getListSet().

Why can't I assign dummy.getListSet() to a Set<List<?>>?

2

There are 2 best solutions below

0
MaKri On

First is important to know, that the compiler replace ? operator with Object class. So when you write this:

DummyClass<?> dummy

your class definition will look like this:

public class DummyClass<Object>

and methods like this:

public List<Object> getList() {
    return new ArrayList<Object>();
}
public Set<List<Object>> getListSet() {
    return new HashSet<List<Object>>();
}

You can write

List<?> list = new List<Object>();

but not

Set<List<?>> set = new HashSet<List<Object>>();
0
s106mo On

However you can do following:

Set<? extends List<?>> listSet = listSet = dummyClass.getListSet();

See the excellent article Generics gotchas.