在 C++ 中,您需要手动删除 LinkedList 中的节点:
Node* node1 = new Node(s);
Node* node2 = new Node(s);
Node* node3 = new Node(s);
node1 -> next = node2;
node2 -> next = node3;
//remove node2 by:
delete node2;
node1 -> next = node3;
对于 Java(这是我学习它的前两天)如何自动 垃圾收集知道什么时候采取行动?会:
node1.next = node3;
足够了吗?
最佳答案
一旦范围内没有对它的引用,java 中的对象将有资格进行垃圾回收。
所以如果你有一个像这样的单向链表
(1) -> (2) -> (3)
并假设 head = node 1
那么是的,设置 head.next = head.next.next
将允许 node 2
在某个时候被 GC。
但是,在您的示例中,您的 node2
在您明确声明之前无法消失
node2 = null
除了 node1.next = node3
之外,因为作为 node2
的引用会将其保留在范围内。
请注意,node2 = null
实际上并未对 node2
过去指向的 Node
对象执行任何操作。相反,它只是将引用(因为 java 中的所有对象实际上都是指针)设置为 null。
关于Java - LinkedList 的自动垃圾回收是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33183558/