gpt4 book ai didi

java - Java中的通用集合和通配符

转载 作者:搜寻专家 更新时间:2023-11-01 04:06:42 25 4
gpt4 key购买 nike

在以下情况下,我无法理解泛型,请参阅下面的内联评论以了解我的问题:

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。你和编译器都不知道那是什么?是,所以您无法向该 Set 添加任何内容。

您可以将集合的值分配给 AbstractGroup 类型的变量,但反之则不行。

相反,你需要这个:

Set<? super AbstractGroup> test;

这个原则有时被称为PECS并解释得很好in this answer .

关于java - Java中的通用集合和通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7363170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com