Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure that objects implement 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

like image 602
evermean Avatar asked Jul 02 '10 14:07

evermean


2 Answers

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.

like image 117
Michael Myers Avatar answered Sep 28 '22 03:09

Michael Myers


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

like image 45
Lyle Avatar answered Sep 28 '22 03:09

Lyle