将Generic类的子类分配给该类的超类 [英] Assign a subclass of a Generic class to a super class of this class
问题描述
我有几个提供的接口
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();
}
以及实现第一个类的类:
public class SimpleFinder< S extends Stack< T>,T extends Item>实现Finder< S,T> {
public S find(S s,int a){
S stack = ....;
...
stack = s.getCopy(); \\错误:不兼容的类型
\\ required:S
\\ found:Stack< T>
.....
返回堆栈;
}
}
如果我不行改变任何接口什么是最好的行为,同时保持实现尽可能通用?
编辑
其他一些代码我不能破坏实例化 SimpleFinder< ClassA,ClassB>
,所以我应该在实现中有两个泛型类型。
S扩展Stack< T>
。 Java是强类型的,不会让你做这样的事情。 您可以转换为 Stack< T>
,在这种情况下,您仍然会收到关于未经检查转换的警告。这意味着这种转换是不安全的。
public class SimpleFinder< S extends Stack< T> ;, T扩展项目>实现Finder< S,T> {
@Override
public S find(S s,int a){
Stack< T> stack = s.getCopy();
返回(S)堆栈;
}
}
或简单地使用 Stack< T>
代替 S延伸Stack< T>
,这是我的建议:
public class SimpleFinder< T extends Item>实现Finder< Stack> T>,T> {
@Override
public Stack< T> find(Stack< T> s,int a){
Stack< T> stack = s.getCopy();
返回堆栈;
}
}
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.
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;
}
}
这篇关于将Generic类的子类分配给该类的超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!