确保对象实现Comparable [英] Ensure that objects implement Comparable

查看:95
本文介绍了确保对象实现Comparable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,想知道如何解决它。我有一个通用类 Tuple< A,B> 现在我想根据A和B排序他们的元组。它应该看起来像这样:

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:

未分类:


(1,5)
(2,8)
(6,8)
(1,4)
(2,4)

排序: / p>

Sorted:


(1,4)
(1,5)
(2,4)
(2,8)
(6,8)



因为这个原因,我想到了实现一个通用的比较方法c> public int compareTo(Tuple< A,B> other))。唯一的问题是,你可以参数化类的所有对象(例如A = Integer,B = String)必须实现compareTo方法,以使这整个工作。

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.

有没有办法确保Tuple可以容纳的所有对象都实现了Comparable接口?

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?

感谢

推荐答案

您可以使用递归类型边界也是 Effective Java 的第27项)指定元组的组件扩展Comparable ,像这样:

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:

 public class Tuple<A extends Comparable<? super A>, B extends Comparable<? super A>> implements Comparable<Tuple<A, B>> {
    A valueA;
    B valueB;

    @Override
    public int compareTo(Tuple<A, B> tuple) {
        // Implement comparison logic
        return 0;
    }
}

这允许您为组件指定不同类型元组(Tuple< Integer,String>)。

This allows you to specify different types for the components of the tuple (Tuple<Integer, String>).

这篇关于确保对象实现Comparable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆