定义一个实现可比较的接口

发布于 2024-12-18 06:32:41 字数 418 浏览 1 评论 0原文

我试图定义一个接口,以便所有实现类都必须与它们自己及其子类进行比较。

例如,考虑:

public interface Rating implements Comparable<Rating> {}

这意味着实现类必须与所有评级相比较:

public class A implements Rating {
    public int compareTo(Rating r) {return 0;}
}

我想放宽该要求,以便我可以定义一个类,例如:

public class A implements Rating {
    public int compareTo(A a) {return 0;}
}

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;}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我一向站在原地 2024-12-25 06:32:41

我希望您尝试得到这样的东西:

public class Rating implements Comparable<? extends Rating> {
   ...
}

或者也许(虽然我不确定您能做到这一点):

public interface Rating extends Comparable<? extends Rating> {
   ...
}

请参阅 Oracle 的此页面 了解有关有界通配符的更多信息。

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.

离不开的别离 2024-12-25 06:32:41
  1. 我想你可能希望你的“compareTo()”返回除“0”之外的东西;)

  2. 您可以使用“instanceof”来查看任意对象是否是某个特定类(或子类)

  3. I不确定是否超载“compareTo()”必然是个好主意。您甚至可能希望将输入参数设置为“Object o”。

恕我直言..pSM

  1. I imagine you probably want your "compareTo()" to return something besides "0" ;)

  2. You can use "instanceof" to see if an arbitrary object is some particular class (or a subclass)

  3. I'm not sure overloading "compareTo()" is necessarily a good idea. You might even want to make the input argument "Object o".

IMHO .. pSM

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文