Search code examples
javagenericscomparablecomparetocannot-find-symbol

compareTo with generic linkedList


I am new to java and i have encountered a problem while making a generic class with comparable interface. In the sortedInsert method of LinkedList class it gives error on head.value.compareTo(new_node.value), i am making an object of Linkedlist class in main so , according to my understanding head.value should give me an employee object for which i am calling compareTo . but still it gives me this error . is there anything i understood incorrectly ? or making a mistake in this code .

cannot find symbol symbol: method compareTo(T)

public class Employee implements Comparable<Employee>
{
private int empID;
private String name;
private int salary;
private boolean manager;
private int subordinates;

public Employee()
{
    empID = 0;
    name = "";
    salary = 0;
    manager = false;
    subordinates = 0;
}



public Employee(int id , String name , int salary , boolean manager , int sub)
{
    empID = id;
    this.name = name;
    this.salary = salary;
    this.manager = manager;
    subordinates = sub;
}

public int  GetID()
{
    return this.empID;
}


public String GetName()
{
    return this.name;
}

@Override
public int compareTo(Employee other)
{
    if (this.empID < other.empID)
    {
        return -1;
    }
    else if (this.empID > other.empID)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}


public class LinkedList<T>
   {
    private int count;
    private Node<T> head;



    private class Node<T>
    {
        public T value;
        public Node<T> next;


        public Node(T data)
        {
            this.value = data;
            this.next = null;
        }


    }


    LinkedList()
    {
        count = 0;
        head = null;
    }



    void sortedInsert(T data)
    {

        Node<T> current;
Node<T> new_node = new Node<T>(data);

         /* Special case for head node
           head.value >= newNode*/

        if (head == null || (head.value.compareTo(new_node.value) == 1 || head.value.compareTo(new_node.value) == 0))
        {
            new_node.next = head;
            head = new_node;
        }
        else {


            current = head;

            while (current.next != null && (current.next.value.compareTo(new_node.value) == -1))
                current = current.next;

            new_node.next = current.next;
            current.next = new_node;
        }
    }

Solution

  • You could try to switch to this:

    public class LinkedList<T extends Comparable<T>>