0

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

1

2 Answers 2

1

However you can do following:

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

See the excellent article Generics gotchas.

-1

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>>();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.