我在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
,依此类推...
how should i proceed.
- 创建一个新节点
- 将新节点的
下一个
指向头的下一个
- 将
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/