2

A newbie question (possibly duplicate too) but can someone point me what's wrong with the below code:

public class Node<T> implements Comparable<Node<T>> {

    protected final Comparable<T> data;
    protected final List<Node<T>> adj;

    public Node(Comparable<T> data) {
        this.data = data;
        adj = new ArrayList<Node<T>>();
    }

    @Override
    public int compareTo(Node<T> other) {
        return data.compareTo(other.data);
    }
}

The compareTo method shows a compilation error: compareTo(T) in Comparable cannot be applied to (java.lang.Comparable).

Alternatively I tried using public class Node<T extends Comparable<? super T>> implements Comparable<Node<T>> but then if I add this Node in, say, an ArrayList> then I am not able to use the contains method of ArrayList. I'd be very thankful if someone points me out the difference.

1 Answer 1

5

You need to tell Java that T extends Comparable<T>, like this:

public static class Node<T extends Comparable<T>> implements Comparable<Node<T>> {

    protected final T data;
    protected final List<Node<T>> adj;

    public Node(T data) {
        this.data = data;
        adj = new ArrayList<Node<T>>();
    }

    @Override
    public int compareTo(Node<T> other) {
        return data.compareTo(other.data);
    }
}

Comparable<T> says that you can apply compareTo method to an object of type T. When your version declared

Comparable<T> data

and then tried to compare data to Comparable<T> instead of T, the compiler objected, because T and Comparable<T> are incompatible.

NOTE: For greater flexibility, use Node<T extends Comparable<? super T>>. This would let you mix and match nodes based on different subclasses in the same comparison (thanks, JB Nizet, for a great suggestion).

Sign up to request clarification or add additional context in comments.

3 Comments

Agreed. I would use Node<T extends Comparable<? super T>> though.
Yes, I tried the suggestion and it works nicely, although I was interested to know if I do Comparable<T> data instead of 'T data' then why does compiler throw error when I do overridden compareTo(<Node<T> other) { data.compareTo(other.data); }
Ah, got it. Posted my comment before seeing the edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.