简体   繁体   中英

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

I want to create an interface that, beyond other method signatures, will have a signature of this type:

Set<Instruction> parse(String rawData);

And in classes implementing the interface, I want to do as an implementation:

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

Where DerivedInstruction extends the Instruction abstract class. (Instruction could also be an interface, alternatively).

My point is not on the Collection type (I know HashSet implements Set), but on generic types. By searching on it, I found that both Set<Instruction> and HashSet<SpecificInstruction> extend the Object type, and are not related via inheritance (at least not directly). Therefore, I can not upcast HashSet<SpecificInstruction> on returning type. Any ideas on how to do this? Thank you.

Here's an example how you could relax the type constraints on your parse methods:

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

The full example:

interface Instruction {}
class DerivedInstruction implements Instruction {}

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

Therefore, I can not upcast HashSet on returning type. Any ideas on how to do this? Thank you.

Then you need to use the means of a bounded wildcard: Set<? extends Instruction> Set<? extends Instruction> . The ? stands for an unknown type which is in fact a subtype of Instruction or type of Instruction itself. We say that Instruction is the upper bound of the wildcard.

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

Read about this more here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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