Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

java - Assign a subclass of a Generic class to a super class of this class

I have couple of supplied interfaces

public interface Finder<S extends Stack<T>,T extends Item> {
    public S find(S s, int a);
}

public interface Stack<T extends Item> {
    Stack<T> getCopy();
}

and a class that implements the first:

public class SimpleFinder<S extends Stack<T>,T extends Item> implements Finder<S,T>{

    public S find(S s, int a){
         S stack = ....;
         ...
         stack = s.getCopy(); \Error: incompatible types
                              \       required: S
                              \       found:    Stack<T>
        .....
        return stack;
    }


}

If I cannot change any interface what would be the best course of action while keeping the implementation as generic as possible?

EDIT Some other code which I cannot break instantiates SimpleFinder<ClassA,ClassB> so I should have two generic types in the implementation as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that obviously Stack<T> is not S extends Stack<T>. Java is strongly typed and won't let you do such things.

You can either cast to Stack<T>, in which case you will still get a warning about unchecked conversion. This means this conversion is unsafe.

public class SimpleFinder<S extends Stack<T>, T extends Item> implements Finder<S, T> {

    @Override
    public S find(S s, int a) {
        Stack<T> stack = s.getCopy();
        return (S) stack;
    }

}

or simply use Stack<T> instead of S extends Stack<T>, which is my recommendation:

public class SimpleFinder<T extends Item> implements Finder<Stack<T>, T> {

    @Override
    public Stack<T> find(Stack<T> s, int a) {
        Stack<T> stack = s.getCopy();
        return stack;
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...