会 Java 垃圾收集器 运行 吗?

Will Java garbage collector run?

节点class给出如下:

// I have not added class modifiers for simplicity
class Node{
 
 int data;
 Node next;

//Constructor
Node(int data){
  this.data = data;
  next = null;
  }
}

假设我有一个数字 n1 、 n2 、 n3 等的简单链表(它至少有 2 个节点)。我们只能使用头指针来引用链表。头指针指向 n1 节点。现在有一个我们传递头节点的删除节点功能。

Node deleteNode(Node head){

  if(head==null)
   return null;
  
 else
   return head.next;
  
}

假设我们运行 删除节点函数一次。 java 的垃圾收集器是否会删除 n1 节点,因为现在我们无法访问它但节点 n1 仍指向 n2(在 delete Node 函数中我们没有使“next”参数指向 null)?我们刚刚更改了头指针。

根据您的代码片段,垃圾收集器不会 运行。

您的 Node deleteNode(Node head) 没有删除任何内容,您只是返回下一个节点(如果有的话)。

为了让垃圾收集器 运行 您必须丢弃对此处未发生的对象的所有引用。

如果没有可达的引用,对象将被垃圾回收。

例如,如果您像这样初始化链表:

Node head = new Node(0);
Node n1 = new Node(1);
Node n2 = new Node(2);
head.setNext(n1); //Let's assume that you have the basic getters and setters implemented
n1.setNext(n2);

如果你这样做,那么你的原始头部将被标记为垃圾收集:

head = deleteNode(head); //Here head will be referencig n1, so nothing is referencing the original head anymore, so it will be garbage collected somewhere in the future

(旁注:您不必在构造函数中将 class 的字段初始化为 null,因为它们默认为 null)