繁体   English   中英

有没有办法将Java Collections与扩展类类型一起使用?

[英]Is there a way to use Java Collections with extended class types?

我想创建一个接口,除了其他方法签名外,还将具有这种类型的签名:

Set<Instruction> parse(String rawData);

在实现该接口的类中,我想作为一个实现:

 Set<Instruction> parse(String rawData){
   //Do work.
   //return an object of type HashSet<DerivedInstruction>.
 }

DerivedInstruction在哪里扩展了Instruction抽象类。 (指令也可以是接口)。

我的观点不是关于Collection类型(我知道HashSet实现Set),而是关于泛型类型。 通过搜索,我发现Set<Instruction>HashSet<SpecificInstruction>扩展了Object类型,并且不通过继承关联(至少不是直接关联)。 因此,我不能在返回类型上转换HashSet<SpecificInstruction> 有关如何执行此操作的任何想法? 谢谢。

这是一个示例,您可以如何放松parse方法上的类型约束:

Set<? extends Instruction> parse(String rawData) {
    //....
}

完整的例子:

interface Instruction {}
class DerivedInstruction implements Instruction {}

Set<? extends Instruction> parse(String rawData){
    return new HashSet<DerivedInstruction>();
}

因此,我不能在返回类型时转换HashSet。 有关如何执行此操作的任何想法? 谢谢。

然后,您需要使用有界通配符的方法: Set<? extends Instruction> Set<? extends Instruction> ? 代表未知类型,实际上是Instruction的子类型或Instruction本身。 我们说Instruction是通配符的上限。

Set<? extends Instruction> parse(String rawData){
   //Do work.
   //return an object of type HashSet<DerivedInstruction>.
 }

在这里了解更多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM