java中的通用集合和通配符
发布时间:2020-12-15 05:06:56 所属栏目: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 com
在以下情况下我遇到问题,请参阅下面的内联评论:
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并且很好地解释了in this answer. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |