user3091733
user3091733

Reputation: 11

Implementing compareTo() method in a Generic class

I have a project I'm working on and this is what I have started with:

public class Pair<T extends Comparable, E extends Comparable> implements Comparable{

    private E e;
    private T t;

    public int compareTo(Pair arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

}

I need to use this class to sort ordered pairs in ascending order. If the first ones are equal, then it should sort by the send point.

Could you guys please help me get a start on this?

Upvotes: 1

Views: 2473

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

In your class definition, your T and E generics lack the comparison against themselves. This also happens for your Pair class. The definition of the class should be:

public class Pair<T extends Comparable<T>, E extends Comparable<E>> implements Comparable<Pair<T, E>> {

}

Now you can define how to compare the pair. Here's an example:

public class Pair<T extends Comparable<T>, E extends Comparable<E>> implements Comparable<Pair<T, E>> {
    private E e;
    private T t;

    public int compareTo(Pair<T, E> pair) {
        int result = t.compareTo(pair.t);
        return (result == 0) ? e.compareTo(pair.e) : result;
    }
}

Upvotes: 8

Related Questions