Ensure that objects implement Comparable

£可爱£侵袭症+ 提交于 2019-12-12 10:54:33

问题


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


回答1:


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

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




回答2:


If you declare the class as

public class Tuple<A extends Comparable<? super A>,
                   B extends Comparable<? super B>> { ...

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.




回答3:


This should do the trick. Any class you specify will have to extend Comparable.

public class Tuple<? extends Comparable> {
}


来源:https://stackoverflow.com/questions/3166816/ensure-that-objects-implement-comparable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!