Generic collection & wildcard in java

collections, generics, java, wildcard

Solution

//Intuitively I would expect this to mean that test is set containing objects 
//that subclass AbstractGroup
Set<? extends AbstractGroup> test;

Nope, it means that it's a set of one specific ? which extends AbstractGroup. And neither you nor the Compiler have any way of knowing what that ? is, so there's no way you can add anything to that Set.

You can assign the set's values to variables of type AbstractGroup, but not the other way around.

Instead, you need this:

Set<? super AbstractGroup> test;

This principle is sometimes called PECS and explained well in this answer.

Problem

I am having problems getting my head around generics in the following situation, see inline comments below for my questions: ``` public void exampleMethod() { //Intuitively I would expect this to mean that test is set containing objects //that subclass AbstractGroup Set<? extends AbstractGroup> test; //Yet the compiler complains here and I do not understand why? test.add(new AnyAbstractGroupSubGroup()); //I would guess that a method call such as this at runtime test = new HashSet<SubGroupA>() //would mean that only objects of subgroupA can be added to the collection, but then //what is the point in using the wildcard in the first place? } ```

Original source

Related problems