3

I am having trouble understanding why the compiler is not allowing the following assignment:

Consumer<Collection<? super Project>> consumer = new Consumer<Collection<Project>>(){};

I generally understand how to use "? super ..." and understand why it works fine in these similar examples:

Consumer<? super Project> projectConsumer = new Consumer<Project>(){};

or

Consumer<? super Project> objectConsumer = new Consumer<Object>(){};

or even

Collection<? super Project> objectCollection = new ArrayList<Object>();

However I don't see how these differ from the first example. Could someone please explain why the first example does not compile?

4
  • 1
    They differ because the nesting indeed makes a difference. A wildcard at the outermost level of the type argument expresses the possibility of multiple conforming types. A wildcard more deeply nested, on the other hand, is an inherent part of the type argument. Commented Oct 11, 2017 at 18:33
  • Consumer<? extends Collection<? super Project>> would work. It's the same reason you can't assign a List<Dog> to a List<Animal>. Commented Oct 11, 2017 at 18:33
  • Consider List<List<?>>: a List that can accept any List as an element. For example, it allows both a List<Integer> and a List<String> as elements, at the same time. Neither a List<List<String>> nor a List<List<Integer>> can do that, so neither of them is a subtype of List<List<?>>. Commented Oct 11, 2017 at 18:38
  • Possible duplicate of Java generics compiler error Commented Oct 11, 2017 at 19:46

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.