java - 使用递归类定义创建第一个对象

标签 java list class generics

我在java中做了一些实验,偶然发现了这个问题

假设我有一个具有此递归定义的类

public class Node<T> implements Iterable<T>{
    public final T element;
    public final Node<T> next;

    public Node(T head, Node<T> tail) {
        this.element = head;
        this.next = tail;
    }
// Contains few more methods and implementation of iteratable like add, remove etc
}

现在,问题是我将使用这个类作为另一个带有final关键字的类中的字段。现在,如果一开始我要创建一个空列表,然后将其添加到列表中,我应该如何继续。

让事情变得简单

class NodeList <T>{
    private final Node<T> head;

    public NodeList(){
    }

    // Few more functions
}

使用 NodeList 类如何创建一个空列表,然后使用添加函数添加数据

最佳答案

在java中引用作为指向内存中对象的指针,该对象在内部可以以相同的方式指向另一个对象。

让我们尝试从视觉上理解它:

What happens to the pointer head when the object obj is added to an empty linked list?

您必须从 head 中删除 final 关键字,因为每次添加新节点以指向新节点时,它的引用都会发生变化。

在下面的快照中,head是指向内存中第一个对象的引用,第一个对象包含另一个指向第二个对象的引用next,依此类推...

enter image description here

how should i proceed.

  1. 创建一个新节点
  2. 将新节点的下一个指向头的下一个
  3. head指向新节点
<小时/>

示例代码:

class Node<T> {
    public final T element;
    public final Node<T> next;

    public Node(T head, Node<T> tail) {
        this.element = head;
        this.next = tail;
    }
}

class NodeList<T> {
    private Node<T> head;

    public void add(T value) {
        if (head != null) { 
            Node<T> node = new Node<T>(value, head); // create a new node 
            head = node;   // point `head` to new node 
        } else {
            // if head is null then assign it to head
            head = new Node<T>(value, null);
        }
    }
}

NodeList<String> nodeList = new NodeList<String>();
nodeList.add("First");
nodeList.add("Second");
nodeList.add("Third");

// print all nodes
Node<String> node = nodeList.head;
while (node != null) {
    System.out.println(node.element);
    node = node.next;
}

输出:

Third
Second
First

关于java - 使用递归类定义创建第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25407292/

相关文章:

java - 即使 jar 位于/lib 中,也会抛出 "java.lang.ClassNotFoundException: org.apache.commons.io.FileUtils"

java - 如何使用 PCF 将 QueueManager 作为部分存储库添加到集群?

python - 列表与列表的列表的乘法

c++ - 如何访问前向声明类的成员

c++ - 将类的所有成员复制到当前对象

c++ - 无法访问类的成员

java - 启动 Coherence 集群时的 PartitionLostEvent

java - 是否始终调用 gc,即使堆空间在运行时连续可用?

R 变量中的变长向量或列表

Python - 嵌套列表 : One line code