簡體   English   中英

java中的通用集合和通配符

[英]Generic collection & wildcard in java

在以下情況下我遇到問題,請參閱下面的內聯評論:

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

不,這意味着它是一組特定的? 它擴展了AbstractGroup。 你和編制者都沒有辦法知道那是什么? 是的,所以你無法向該套裝添加任何東西。

您可以將集合的值分配給AbstractGroup類型的變量,但不能相反。

相反,你需要這個:

Set<? super AbstractGroup> test;

這個原則有時被稱為PECS ,並在這個答案中得到了很好的解釋。

Set<? extends AbstractGroup> test;

這意味着您的集合可以是擴展AbstractGroup的任何對象的集合,但通常編譯器不允許您向該集合添加內容(因為它無法判斷您是否SubGroupB添加到Set<SubGroupA>等)。

test = new HashSet<SubGroupA>()

您的實際集只包含SubGroupA類型的SubGroupA及其子類。 但是,編譯器仍然不知道test的內容是什么(見上文)。

that map to AbstractGroup (which the compiler checks for). 通配符的要點是:您可以將任何集合分配給使用AbstractGroup或子類參數化的變量,從而確保您可以將該映射中所有對象AbstractGroup (編譯器檢查)。

如果您想擁有一個可以包含任何AbstractGroup對象的集合,則不要使用通配符。

//this would compile (under the assumption that SubGroupA extends AbstractGroup)
Set<? extends AbstractGroup> test = new HashSet<SubGroupA>(); 

//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<AbstractGroup> test = new HashSet<SubGroupA>();

//this would compile
Set<AbstractGroup> test = new HashSet<AbstractGroup>();
test.add(new SubGroupA());

你不需要這里的通配符在你的情況下,它就足夠了

Set<AbstractGroup> test;

然后,您可以將AbstractGroup的任何子類放入集合中。

此外,它看起來不像您在上面的代碼中初始化測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM