簡體   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