Search code examples
javacomparable

How to compare E elements


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


Solution

  • 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);
        }
    }