确保对象实现 Comparable
我有一个小问题,想知道如何解决它。我有一个通用类 Tuple
现在我想根据 A 和 B 对它们的元组进行排序。它应该如下所示:
Unsorted:
(1,5) (2,8) (6,8) (1,4) (2,4)
Sorted:
(1,4) (1,5) (2,4) (2,8) (6,8)
因此我考虑实现Tuple 类中的通用比较方法 (public intcompareTo(Tupleother)
)。唯一的问题是,您可以参数化类的所有对象(例如 A=Integer、B=String)也必须实现compareTo 方法才能使整个事情正常工作。
有没有办法确保Tuple可以容纳的所有对象都实现Comparable接口?
或者对于如何解决这个问题还有其他建议吗?
谢谢
I have a litte problem and was wondering how to solve it. I have a generic class Tuple<A,B>
and now I would like to sort their tuples according to A and B. It should look like this:
Unsorted:
(1,5) (2,8) (6,8) (1,4) (2,4)
Sorted:
(1,4) (1,5) (2,4) (2,8) (6,8)
For that reason I thought of implementing a generic compare method (public int compareTo(Tuple<A, B> other)
) in the Tuple class. The only problem is that all objects that you could parameterize the class for (e.g. A=Integer, B=String) have to implement the compareTo method too in order for this whole thing to work.
Is there a way to ensure that all objects the Tuple can hold implement the Comparable interface?
Or are there any other suggestions on how to solve this problem?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您将类声明为
then ,则可以确保 A 和 B 都是可自比较的。然后,您可以对类中具有的类型 A 或 B 的任何对象调用
compareTo()
。If you declare the class as
then that ensures that both A and B are self-comparable. You can then call
compareTo()
on any object of type A or B that you have in the class.您可以使用递归类型界限(另请参阅 Effective Java 的第 27 项)来指定元组的组件扩展了 Comparable,如下所示:
这允许您为元组的组件指定不同的类型(Tuple)。
You could use recursive type bounds (see also Item 27 of Effective Java) to specify that the components of the tuple extend Comparable, like so:
This allows you to specify different types for the components of the tuple (Tuple<Integer, String>).
这应该可以解决问题。您指定的任何类都必须扩展 Comparable。
This should do the trick. Any class you specify will have to extend Comparable.