Java 如何实现泛型<;E>;在链接列表中?

Java 如何实现泛型<;E>;在链接列表中?,java,generics,linked-list,Java,Generics,Linked List,我一直在尝试创建一个链表,它使用泛型返回用户选择的数据类型。问题是我的方法public E-get(int-sub) 无法识别我的返回光标。内容为类型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;

我一直在尝试创建一个链表,它使用泛型返回用户选择的数据类型。问题是我的方法
public E-get(int-sub)
无法识别我的
返回光标。内容
为类型
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; 
    }
}
public E-get(int-sub)
{
Node cursor=head;//从链表的开头开始。

对于(int c=1;c这些是带有类型化参数的类的一部分,例如
MyLinkedList
?问题可能是您也向Node类添加了一个
类型参数,它可能引用一个不同的类
E
,而该类不一定与外部类引用的
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; 
    }
}
public E-get(int-sub)
{
Node cursor=head;//这里忘记了泛型
对于(int c=1;c,在您的方法中

public E get(int sub)
将光标初始化为节点,而不是
节点

这将导致元素类型为Object,这是您编写时得到的

return cursor.contents;
要解决:


使用
节点
或显式强制转换返回到
E

的get方法不是位于节点类中吗?我向节点游标添加了泛型以使其成为节点游标,但现在当我使用下面的代码测试它时,它会给我一个新的错误,我无法理解为什么我的代码不会返回正确的输出。public class Demo1{publicstaticvoidmain(String[]args){MyLinkedList t=newmylinkedlist();t.add(“千橡树”);for(int x=0;x
。您应该解释OP哪里出错,而不是仅提供可粘贴副本的答案(可能还有更多;)我认为有趣的是注意到原始返回类型与声明的返回类型如何以及为什么不一致。
return cursor.contents;