compareTo与通用的linkedList

时间:2017-08-26 13:41:04

标签: java generics comparable compareto cannot-find-symbol

我是java的新手,我在制作具有类似界面的泛型类时遇到了问题。在LinkedList类的sortedInsert方法中,它在head.value.compareTo(new_node.value)上给出了错误,我在main中创建了一个Linkedlist类的对象,所以根据我的理解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;
        }
    }

2 个答案:

答案 0 :(得分:0)

你可以尝试切换到这个:

public class LinkedList<T extends Comparable<T>>

答案 1 :(得分:0)

function fTwo(){ if (localStorage.getItem("myJson") !== null) { var passedJson = localStorage.getItem("myJson"); //get saved data anytime } } 变量不一定是实现Comparable接口的东西。您需要定义head.value,以便它必须实现LinkedList<T>(请参阅@ algrid的答案)或在使用Comparable方法时强制转换它。