How to compare generic nodes in a linked list usin

2019-06-18 07:14发布

I am implementing a sorted list using linked lists. My node class looks like this

public class Node<E>{
    E elem;
    Node<E> next, previous;
}

In the sorted list class I have the add method, where I need to compare generic objects based on their implementation of compareTo() methods, but I get this syntax error "The method compareTo(E) is undefined for type E". I have tried implemnting the compareTo method in Node, but then I can't call any of object's methods, because E is generic type. Here is the non-finished body of add(E elem) method.

public void add(E elem) 
{

        Node<E> temp = new Node<E>();
        temp.elem = elem;

        if( isEmpty() ) {           
            temp.next = head;
            head.previous = temp;
            head = temp;
            counter++; 
        }else{
            for(Node<E> cur = head; cur.next != null ; cur= cur.next) {
                **if(temp.elem.comparTo(cur.elem)) {**
                    //do the sort;

                }/*else{
                    cur.previous = temp;
                }*/             
            }
            //else insert at the end

        }
}

Here is one of the object implemnting compareTo method

public class Patient implements Comparable<Patient>{
    public int compareTo(Patient that)
    {
        return (this.getPriority() <= that.getPriority() ? 1 : 0 );
    }
}

4条回答
Evening l夕情丶
2楼-- · 2019-06-18 07:31

If you want the elements stored in your nodes to be comparable, you can state this using generics:

public class Node<E extends Comparable<E>> {

    E elem;
    Node<E> next, previous;
}

this way it is sure, that every E implements the Comparable interface, so you can safely call the compareTo method.

查看更多
闹够了就滚
3楼-- · 2019-06-18 07:36

Try

public class Node<E extends Comparable<E>>{
    E elem;
    Node<E> next, previous;
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-06-18 07:44

Bound E to Comparable:

public class Node<E extends Comparable<E>>{
    E elem;
    Node<E> next, previous;
}

It will compile now.

查看更多
在下西门庆
5楼-- · 2019-06-18 07:55

It seems that your generic E must be E extends Comparable<E>. This way you will get the access to the compareTo(E other) method. However, you will be unable to add elements that are not implementing this interface.

查看更多
登录 后发表回答