java - 这本教科书链表是否涉及 "recursive constructor"?

标签 java generics linked-list

这是来自教科书实现的链表类的片段:

public class ListItem
{
  Object   item;                  
  ListItem next;                  

  public ListItem(Object item) 
  {
    this.item = item;             
    next      = null;                  
  }
}

它看起来像递归 - 类 ListItem 具有名为 ListItem 的实例变量。调用这个递归是否正确?

以下是我在 Pascal 中定义链表的方法。我看到了您可能称之为递归的提示(pNodeType,又名 ^NodeType),但感觉与上面的 Java 代码片段不同:

type
    **pNodeType** = ^NodeType ;  

    NodeType = record        
      name : string ;        
      next : **pNodeType** ;  // conceptually, change the type to **^NodeType**
    end ;

所以我想既然 Java 缺乏指针而对象是引用,我毕竟在看同样的事情。对吗?

因此,如果我想要一个双向链表(也向后),我会添加一个实例变量,如下所示

ListItem prev;

并像这样向构造函数添加一行代码

prev = null;

并采取与前向链接工作相同的谨慎程度。

对吗?

最后,如果我想要一个通用链接列表,我只需像这样更改代码片段,并将方法中所有出现的“Object”更改为“E”):

public class ListItem<E> {

  E item;                    
  ListItem next;                     

  public ListItem(E item) {
    this.item = item;                              
    next = null;                                   
  }
}

对吗?

最佳答案

没有递归。

当您声明与类相同类型的字段时,您不会实例化实例。

<小时/>

您的构造函数是否包含初始化:

next = new ListItem(null);

或者声明包含初始化:

ListItem next = new ListItem(null);

会有递归

<小时/>

关于一般问题,您也需要输入该字段:

public class ListItem<E> {

  E item;                    
  ListItem<E> next;  // Added generic parameter                

  public ListItem(E item) {
    this.item = item;                              
  }
}
<小时/>

请注意,您不需要编码:

next = null;  // redundant

因为默认的初始化值已经是null了。

关于java - 这本教科书链表是否涉及 "recursive constructor"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19170710/

相关文章:

java - Java 比较排序数字

Java FileWriter 拒绝覆盖

java - JSON-Simple 导致编译器警告 "Type safety: The method put(Object, Object) belongs to the raw type HashMap."

c - 单链表数组不会删除节点

java - 如何在 LibGDX 中绕圆旋转 Sprite?

java - 执行 mvn clean package : InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty 时出错

oracle - Oracle PL/SQL 中的动态类型或泛型

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

java - 这个链表是循环实现的吗?

c - 链表从大到小排序