[英]Defining an interface that implements comparable
I'm trying to define an interface such that all implementing classes must be Comparable to themselves and their subclasses. 我试图定义一个接口,以便所有实现的类都必须与它们及其子类可比。
For example, consider: 例如,考虑:
public interface Rating implements Comparable<Rating> {}
This means that implementing classes must be Comparable to all Ratings: 这意味着实现类必须与所有等级都可比:
public class A implements Rating {
public int compareTo(Rating r) {return 0;}
}
I'd like to loosen that requirement so that I can define a class like: 我想放宽该要求,以便可以定义一个类:
public class A implements Rating {
public int compareTo(A a) {return 0;}
}
I expect you're trying to get at something like this: 我希望您正在尝试达到以下目的:
public class Rating implements Comparable<? extends Rating> {
...
}
or maybe (although I'm not sure you can do this): 或也许(尽管我不确定您可以这样做):
public interface Rating extends Comparable<? extends Rating> {
...
}
See this page at Oracle for more information on bounded wildcards. 有关有界通配符的更多信息,请参见Oracle上的此页面 。
I imagine you probably want your "compareTo()" to return something besides "0" ;) 我想您可能希望您的“ compareTo()”返回除“ 0”以外的值;)
You can use "instanceof" to see if an arbitrary object is some particular class (or a subclass) 您可以使用“ instanceof”来查看任意对象是否是某个特定的类(或子类)
I'm not sure overloading "compareTo()" is necessarily a good idea. 我不确定重载“ compareTo()”是否一定是个好主意。 You might even want to make the input argument "Object o". 您甚至可能希望将输入参数设为“对象o”。
IMHO .. pSM 恕我直言.. pSM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.