问题
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