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
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>).