How to compare common nodes in a linked list using Comparable?

I use a sorted list using linked lists. My node class is as follows:

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

In the sorted class of the class, I have an add method where I need to compare common objects based on their implementation of the compareTo () methods, but I get this syntax error "The compareTo (E) method is undefined for type E". I tried to implement the compareTo method in Node, but then I can’t name any object method, because E is a generic type. Here is the incomplete body of the 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 objects implementing the compareTo method

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

Associated E with comparable:

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

Now it will compile.

+6
source

It seems your general E should be E extends Comparable<E> . This way you get access to the compareTo(E other) method. However, you will not be able to add elements that do not implement this interface.

+3
source

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

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

this way, of course, that every E implements the Comparable interface, so you can safely call the compareTo method.

+3
source

Try

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

Source: https://habr.com/ru/post/890591/


All Articles