Java - LinkedList 的自动垃圾回收是如何工作的?

标签 java c++ garbage-collection

在 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/

相关文章:

java - 匿名文件流重用描述符

c# - ConditionalWeakTable - GC.Collect() 行为,为什么它没有按预期运行?

memory-management - 垃圾回收机制是如何工作的?

c++ - IHTMLElement 到 HWnd

java - 如何使用配置类中定义的方法?

java - Ant 字符串函数?

Java 线程安全 : enum and static methods

java - 将 super/this 构造函数调用中抛出的异常包装到其他异常中

c++ - 链接器错误 : Statically Linking of Boost Serialization Library

c++ - 声明 const 全局变量时是否需要静态?