java - 如何在链表中实现泛型 <E>?

标签 java generics linked-list

我一直在尝试创建一个链接列表,该列表使用泛型返回用户选择的数据类型。问题是我的方法 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/

相关文章:

vb.net - 关于泛型的初学者问题

java - 使用 lambda 在 LinkedList 中查找元素

检查链表是否初始化

c++ - 如何引用 C++ 中所谓的函数?

java - 我想通过java程序在关闭计算机之前检查打开的应用程序

Java:通配符类型不匹配导致编译错误

java - 如何在同一个包中重用已经实现的方法?

java - 分配给更通用类型的引用

java - 如何在从 Maven 自定义插件编译之前扫描当前项目中的类?

java - 你能在字符串拆分中使用零宽度匹配正则表达式吗?