在泛型类 LinkedList 中找不到符号



我是java的新手,即将从c ++背景开始。 我在制作具有类似接口的泛型类时遇到了问题。在 LinkedList 类的 SearchByID 和 SerchByName 方法中,它在 temp.value.getID(( 和 temp.value.getName(( 上给出错误,我正在 main 中制作 Linkedlist 类的对象,所以,根据我的理解,temp.value 应该给我一个员工对象,我正在为其调用 getID,它是员工类的一个函数。但它仍然给了我这个错误.有什么我理解错了吗?或在此代码中出错。

找不到符号符号:方法 getID((

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 extends  Comparable<T>>
{
private int count;
private Node<T> head;

//completely encapsulated Node class from outer world as they dont need it
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;
}

public Node<T> SearchByID(int id)
{
Node<T> temp ;
for (temp = head; temp.value.getID() != id; temp = temp.next);
return temp;
}

public Node<T> SearchByname(String name)
{
Node<T> temp ;
for (temp = head; temp.value.getName() != name; temp = temp.next);
return temp;
}

请记住:Node键入为Node<T>。 默认情况下,T擦除以Object。 因此,您正在尝试调用getID()的方法Object,这肯定不存在

如果你想确保你能够获取具有该方法的对象,那么你需要为它使用一个接口......

public interface IdSearchable {
int getID();
}

。然后把你的元素绑定到那个上面。

public class LinkedList<T extends IdSearchable & Comparable<T>> {
}

我把其余的留给读者练习,因为你的第二种方法也有类似的缺陷。

最好根据需要保持数据结构开放,因为如果没有这种开放性,泛型将变得毫无价值,因为您将用Employee替换每次出现的T

最新更新