我认为这不是 Check if a generic T implements an interface 的副本, 但它可能是 (??).
所以,我想创建一个通用接口(interface),它只允许实现两个接口(interface)的对象。 Alike 是一个服装界面。
public interface AbstractSortedSimpleList<T extends Comparable<T>, Alike> {}
如果我理解正确,Java 现在会尝试创建一个通用接口(interface) AbstractSortedSimpleList<T,Alike>
,这不正是我想要实现的。我要AbstractSortedSimpleList<T>
其中 T 必须同时实现 Comparable<T>
和 Alike
.
以后想开个新类
public class SortedSimpleList<T> implements AbstractSortedSimpleList<T> {}
这里的重点是创建一个 class SortedSimpleList<T>
其中 T 必须实现上述接口(interface)。但是我的代码似乎运行得不是很好。
最佳答案
您可以为类型参数指定多个边界:
public interface AbstractSortedSimpleList<T extends Comparable<T> & Alike>
然后,您的 SortedSimpleList
将如下所示:
class SortedSimpleList<T extends Comparable<T> & Alike> implements AbstractSortedSimpleList<T> {}
参见 JLS §4.4:
Every type variable declared as a type parameter has a bound. If no bound is declared for a type variable, Object is assumed. If a bound is declared, it consists of either:
a single type variable T, or
a class or interface type T possibly followed by interface types I1 & ... & In.
注意:
不过,您不能为通配符设置如此多的界限。它仅适用于类型参数。
引用资料:
关于java - 如何定义实现两个接口(interface)的泛型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21857613/