我一直在尝试创建一个链接列表,该列表使用泛型返回用户选择的数据类型。问题是我的方法 public E get(int sub)
无法将我的 return cursor.contents
识别为类型 E generic
。
public E get(int sub)
{
Node cursor = head; //start at the beginning of linked list.
for (int c = 1; c <= sub; c++)
{
cursor = cursor.next; //move forward by one.
}
return cursor.contents;//return the element that the cursor landed on.
}
public class Node <E>
{
public E contents;
@SuppressWarnings("rawtypes")
public Node next = null; //points to the next node
//a method has no return type and has the same name as the class
public Node(E element)
{
this.contents = element;
}
}
如上所示,contents 参数在 Node 中声明为 type E
,但 get 方法不会将 cursor.contents
识别为正确的返回类型。
系统建议我将返回类型更改为 Object
,这不是一个选项。或者我将内容更改为已经完成的 E
类型,但它仍然给我一个编译错误。
最佳答案
那是因为你需要把它改成:
public E get(int sub)
{
Node<E> cursor = head; //you forgot the generics here
for (int c = 1; c <= sub; c++)
{
cursor = cursor.next;
}
return cursor.contents;
}
public class Node <E>
{
public E contents;
public Node<E> next = null; //you also even suppressed the raw type here
public Node(E element)
{
this.contents = element;
}
}
关于java - 如何在链表中实现泛型 <E>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30116041/