我有一个单链表
a->b->c->d->e
a,b,c,d 和 e 是节点类型的对象。我想在遍历列表时删除一个节点,然后使删除的节点成为列表的头部,如下面的代码所示
list.delete(iterator, current);
list.addObjectAtFront(current);
public void delete(ListIterator li, Node node) {
if (li == null) {
throw new NullPointerException();
}
li.next();
if (li.previous() != null) {
li.previous().setNext(node.getNext());
}
}
public void addObjectAtFront(Object o) {
Node newNode = new Node(null, o);
if (this.head != null) {
newNode.setNext(this.head);
this.head = newNode;
} else {
this.head = this.tail = newNode;
}
}
调用上述方法时,假设当前项是c。我期待以下内容
list.delete(iterator, current);
Output: a->b->d->e
list.addObjectAtFront(current);
Output: c->a->b->d->e
我有两个相互矛盾的想法
删除后,c 不再指向任何其他节点,可以在调用第二个方法之前进行垃圾回收。
c 不能被垃圾回收,因为它本身不是 null 并且其中有一些数据。这意味着如果我不需要使用 c;它会一直留在内存中。
哪一个是正确的,或者我完全错了,需要对对象引用有一个全新的理解?
最佳答案
垃圾收集永远不会删除您可以任何方式引用的内存(除非您使用 WeakReference )
也就是说,如果您仍然需要使用该节点,请放心,java 不会将其从您那里回收。作为一名程序员,您不需要考虑垃圾收集器的行为方式,除非它是为了提高性能。 GC 不应影响代码的正确性。
Which of this is correct or have I got it wrong completely and need a fresh understanding of object references?
直接回答,都不是。删除时,您使用对名为 current
的节点的引用。此引用与 c 相同。当 c 被删除时,您仍然有 current 引用它。然后将 current 添加到列表的前面。现在您再次对它有 2 个引用,然后当它从范围中删除时您将丢失当前引用,使您回到 1 个引用。
c 永远不会被垃圾回收。
关于java - 删除 SinglyLinkedList 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19795354/