【发布时间】:2015-05-08 04:55:11
【问题描述】:
我一直在尝试创建一个使用泛型返回用户选择的数据类型的链接列表。问题是我的方法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 参数在节点中被声明为type E,但是get 方法不会将cursor.contents 识别为正确的返回类型。
系统建议我将返回类型更改为Object,这不是一个选项。或者我将内容更改为已经完成的类型E,但它仍然给我一个编译错误。
【问题讨论】:
-
get方法不是位于Node类中吗?
-
我将泛型添加到节点光标以使其成为节点
光标,但是现在当我使用下面的代码对其进行测试时,它给了我一个新错误,我无法弄清楚为什么我的代码不会返回正确的输出。 -
公共类 Demo1 { public static void main(String[] args) { MyLinkedList
t = new MyLinkedList (); t.add("千橡"); for (int x = 0; x
标签: java generics linked-list