Generic collection & wildcard in java

前端 未结 3 994
傲寒
傲寒 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

    Set test;

    This means your set can be a set of any object that extends AbstractGroup, but normally the compiler would not allow you to add something to that set (since it can't tell whether you'd for example add a SubGroupB to a Set etc.).

    test = new HashSet()

    Your actual set would only contain objects of type SubGroupA and subclasses thereof. However, the compiler would still not know what the content of test would be (see above).

    The point of the wild card is: you can assign any set to the variable that is parameterized with AbstractGroup or a subclass, thus assuring you can cast all objects already in that map to AbstractGroup (which the compiler checks for).

    If you want to have a set that can contain any AbstractGroup object, just don't use the wildcard.

    //this would compile (under the assumption that SubGroupA extends AbstractGroup)
    Set test = new HashSet(); 
    
    //this wouldn't compile, since the compiler doesn't know the type of test (it might change at runtime etc.)
    test.add(new SubGroupA());
    
    
    //this wouldn't compile since AbstractGroup and SubGroupA are not the exact same type (hence the wildcard would be needed here)
    Set test = new HashSet();
    
    //this would compile
    Set test = new HashSet();
    test.add(new SubGroupA());
    

提交回复
热议问题