0

So what I am trying to do is compare the nodes of a list. Most of the related questions all over the internet that provides answers for this is to implement the comparable interface.

//This is a nested class
private static class Node<E> implements Comparable<Node<E>> {
    private E element;

    ......
    ......

    public int compareTo(Node<E> o) {
       return element >= o.element ? 1 : 0;
    }
}

The problem with this is it throws a compiler error bad operand types for binary '>=' first type: E; second type: E. I can't even use something like this: return element.compareTo(o.element); because compareTo is not defined.

What can I do to fix this? Most of the solutions for problem like this all over the net doesn't work for me... Please Help. Thanks....

1
  • I'd say that for Node<E> to implement Comparable, E itself should implement Comparable.
    – 9000
    Feb 27, 2020 at 15:06

1 Answer 1

4

You need to declare it as class Node<E extends Comparable<E>>, so that E has its own compareTo method:

private static class Node<E extends Comparable<E>> implements Comparable<Node<E>> {
    private E element;

    public int compareTo(Node<E> o) {
       return element.compareTo(o.element);
    }
}
12
  • 1
    It works for me. If you have some other code that uses E from a different class (maybe the outer class) then that E must extends Comparable<E> too. That is, the error is in the code using the Node class, not in the Node class itself.
    – kaya3
    Feb 27, 2020 at 15:10
  • 1
    Well, edit the question to include a minimal reproducible example that reproduces the error you're talking about, and show the full error message. This code doesn't produce an error by itself.
    – kaya3
    Feb 27, 2020 at 15:12
  • 1
    type argument E is not the same E as type variable E. You must have declared a different type variable name E somewhere else in your code, and you didn't say it is comparable.
    – kaya3
    Feb 27, 2020 at 15:14
  • 1
    @robert I just explained why. If the fix I suggested above doesn't work for you, you need to edit the question as I said.
    – kaya3
    Feb 27, 2020 at 15:14
  • 1
    Well, then the error is in code you didn't include in the question, isn't it? Change the declaration of the outer class the way I said to above.
    – kaya3
    Feb 27, 2020 at 15:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.