与通用链表进行比较

compareTo with generic linkedList

我是 java 的新手,我在制作具有可比较界面的通用 class 时遇到了问题。在 LinkedList class 的 sortedInsert 方法中,它在 head.value.compareTo(new_node.value) 上给出错误,我在 main 中创建一个 Linkedlist class 的对象,所以,根据我的理解 head.value 应该给我一个我正在调用 compareTo 的员工对象。但它仍然给了我这个错误。有什么我理解不正确的吗?或在此代码中犯错误。

找不到符号 符号:方法 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;
        }
    }

你可以尝试切换到这个:

public class LinkedList<T extends Comparable<T>>

head.value 变量不一定实现了 Comparable 接口。您需要定义 LinkedList<T> 使其必须实现 Comparable (请参阅@algrid 的回答)或在使用 compareTo 方法时强制转换它。