2013-11-14 125 views
1

我想创建,超越其他方法签名,都会有这种类型的签名的接口:有没有办法使用扩展类类型的Java集合?

Set<Instruction> parse(String rawData); 

而且在实现接口的类,我想做为一个执行时:

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

其中DerivedInstruction扩展了Instruction抽象类。 (指令也可以是一个接口,或者)。我的观点不是集合类型(我知道HashSet implements集合),而是泛型类型。 通过搜索它,我发现Set<Instruction>HashSet<SpecificInstruction> 扩展Object类型,并通过继承(至少不是直接)不相关。因此,我不能在返回类型上上传HashSet<SpecificInstruction>。任何想法如何做到这一点? 谢谢。

+0

为什么不创建类型的对象'的HashSet '呢? – newacct

+0

我可以,我的重点不在于此,而在于泛型。感谢您的关注! :) –

回答

7

这里有一个例子,你如何可以放松你的parse方法的类型约束:

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

的完整的例子:

interface Instruction {} 
class DerivedInstruction implements Instruction {} 

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

非常好,简单的解释和它的作品很大。谢谢! –

1

因此,我不能向上转型在返回类型的HashSet。关于 的任何想法如何做到这一点?谢谢。

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

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

阅读关于这个more here.

+0

谢谢贤者,我希望我可以选择最好的答案。 –

相关问题