views:

64

answers:

3

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  A: 

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

public class Tuple<? extends Comparable> {
}
BrennaSoft
I realize you wrote this without seeing the original generic declaration of Tuple, so I can't blame you for missing the A and B parameters. But even so, it will cause a warning because you haven't parameterized Comparable.
Michael Myers
+7  A: 

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.

Michael Myers
+3  A: 

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

Lyle
I prefer `A extends Comparable<? super A>`, but +1 for implementing Comparable on the Tuple itself. I should have remembered that.
Michael Myers
You shouldn't use `A extends Comparable<A>`... this won't work with older classes that implement raw `Comparable`, among other things. mmyers's signature with `A extends Comparable<? super A>` is correct.
ColinD
Ah, thanks. I've edited my answer so as not to mislead, and have upvoted mmyers' version.
Lyle