通用收集&通配符在java中 [英] Generic collection & wildcard in java

查看:122
本文介绍了通用收集&通配符在java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下情况时遇到问题,请参阅以下内嵌注释:

  void exampleMethod(){
//直观地,我希望这意味着测试设置包含对象
//子类AbstractGroup
Set< ;? extends AbstractGroup>测试;

//但编译器在这里抱怨,我不明白为什么?

test.add(new AnyAbstractGroupSubGroup());

//我猜想在运行时这样的方法调用

test = new HashSet< SubGroupA>()

//意味着只有subgroupA的对象可以添加到集合,但是
//首先使用通配符是什么意思?
}


解决方案

  //直观地,我希望这意味着测试设置包含对象
//子类AbstractGroup
Set< ;? extends AbstractGroup>测试;

不,这意味着它是一个特定的集合?它扩展了AbstractGroup。你和编译器都没有什么办法知道什么?



您可以将集合的值赋给AbstractGroup类型的变量,而不是相反。 p>

您需要这样:

  Set< ;? super AbstractGroup>测试; 

这个原则有时被称为 PECS ,并解释得很好在此答案


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

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;

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<? super AbstractGroup> test;

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

这篇关于通用收集&amp;通配符在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆