[英]Java Generics Comparator
I am coding with Java Generics. 我正在用Java泛型编码。 I want to define a Binary Tree class generically that will be able to take in any class , and guarantee that that class has the Comparator method compare(T o1, T o2) to see whether I need to follow the right or left subtree for insert into my binary tree.
我想一般地定义一个二叉树类,该类将能够接受任何类,并确保该类具有Comparator方法compare(T o1,T o2)来查看是否需要跟随右侧或左侧子树进行插入进入我的二叉树。
public class treeDB <T implements Comparator> {
//define my binary tree methods
}
That is my best estimation of how to force to implement Comparator method, but the compile throws an error and I don't know enough to know what it wants. 这是我对如何强制实施Comparator方法的最佳估计,但是编译会引发错误,并且我对知道它想要什么还不了解。
try this 尝试这个
class treeDB <T extends Comparator<T>> {
...
Everyone has provided the correct syntax, but you might want to consider using Comparable
as in 每个人都提供了正确的语法,但是您可能要考虑使用
Comparable
如
class treeDB <T extends Comparable<T>>
The differences are subtle, and maybe it isn't the better choice. 差异是细微的,也许不是更好的选择。 But it never hurts to look.
但是看起来永远不会受伤。
Firstly, implements
should be replaced with extends
. 首先,
implements
应及时更换与extends
。 In generics extends
is the keyword which is used even if the generic type implements an interface. 在泛型中,
extends
是一个关键字,即使泛型类型实现了接口,该关键字也被使用。
And secondly, using only Comparator
will result in a warning it being a raw type. 其次,仅使用
Comparator
将导致警告它是原始类型。 You must parameterize it. 您必须对其进行参数化。 This is your solution:
这是您的解决方案:
public class treeDB <T extends Comparator<T>> {
}
这应该是public class treeDB <T extends Comparator>
,而不是public class treeDB <T implements Comparator>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.