【问题标题】:How do I implement generics <E> in a linked List?如何在链接列表中实现泛型 <E>?
【发布时间】: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


【解决方案1】:

那是因为你需要把它改成:

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; 
    }
}

【讨论】:

  • 你应该解释 OP 出了什么问题,而不是仅仅提供一个可复制粘贴的答案
  • 可能还有更多 ;) 我认为有趣的是要注意原始返回类型如何以及为什么与声明的返回类型不一致。
【解决方案2】:

您没有在 Node cursor 变量的声明中设置泛型类型。将其更改为 Node&lt;E&gt; cursor 会发生什么。

另外,您没有提供链表类本身的上下文 - 这就是应该声明通用 &lt;E&gt; 的地方。

【讨论】:

  • 没错,似乎任何一种解决方案都行得通!但是,如果使用第一个解决方案,Node 应该是一个静态类。否则,可以使用 LinkedList 类中的&lt;E&gt;
【解决方案3】:

在你的方法中

public E get(int sub)

您将游标初始化为节点而不是 Node&lt;E&gt;

Node cursor = head; //start at the beginning of linked list. 

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

return cursor.contents;

解决:

要么使用Node&lt;E&gt;,要么将返回显式转换为E

【讨论】:

    【解决方案4】:

    这些是带有类型参数的类的一部分吗,例如MyLinkedList&lt;E&gt;?问题可能是您也向 Node 类添加了一个 &lt;E&gt; 类型参数,它可能引用了一个不同的类 E,它不一定与外部类引用的 E 相同。尝试将Node &lt;E&gt; 更改为Node。看看是否有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多