从<! - ?中检索子类型扩展动物 - >

时间:2016-11-14 18:38:21

标签: java generics bounded-wildcard

现有的Set<Trump>传递给另一个以Set<? extends Politician>为参数的函数。鉴于Set<? extends Politician>仅包含Politician对象或Trump对象。

无法修改Politican类。 Trump类可以修改。

有没有办法干净地执行以下操作,或者如何重新设计派生类(Trump)才能执行此操作?

public Set<Trump> getSetOfTrump(Set<? extends Politician> politicianSet)
{
    //do some processing
    for(Politician pol : politicianSet){ //compiler is ok.. but I dont need Politician Object here
    }

    for(Trump t : politicianSet){ // any way to get Trump Objects out of politicianSet?
    }

} 

2 个答案:

答案 0 :(得分:2)

您必须手动过滤对象:

for(Politician t : politicianSet){ // any way to get Trump Objects out of politicianSet?
  if(t instanceof Trump) {
    //do your magic here
  }
}

instanceof运算符如果t是特朗普(的子类)的实例,则返回true。

答案 1 :(得分:1)

下面的代码可以使用 -

public  Set<Trump> getSetOfTrump(Set<? extends Politician> politicians){
    return  politicians.stream().filter( s  -> s instanceof Trump).map(s ->(Trump)s).collect(Collectors.toSet());
}