Generic collection & wildcard in java

前端 未结 3 997
傲寒
傲寒 2021-01-21 05:18

I am having problems getting my head around generics in the following situation, see inline comments below for my questions:

public void exampleMethod() {
    //         


        
3条回答
  •  悲哀的现实
    2021-01-21 05:51

    //Intuitively I would expect this to mean that test is set containing objects 
    //that subclass AbstractGroup
    Set 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 test;
    

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

提交回复
热议问题