简体   繁体   English

闲逛Java的链表堆栈实现

[英]Loitering in Java's Linked List Stack implementation

Does the concept of loitering exist in java's linked list stack implementation? Java的链表堆栈实现中是否存在游荡的概念? Do I need to free memory by setting a node's contents to null before removing it from a linked list? 在从链表中删除节点之前,是否需要通过将节点的内容设置为null来释放内存? Or is not doing so just as good because there isn't going to be any reference to my old first node anyway? 还是这样做不那么好,因为无论如何都不会引用我的旧第一个节点? Thanks! 谢谢!

public Item pop() {
    if (isEmpty()) 
        throw new StackEmptyException("Stack Empty");
    Item item = first.item;
    first.item = null;
    first = first.next;
    return item;
}

您的第二个语句是正确的-您无需清除节点,Java GC会处理它。

It does exist but it is unlikely you will need to worry about it. 它确实存在,但您不太可能需要担心它。

In your case, after first = first.next the Java GC will recognise that the old node pointed at by first is now unreachable and so can be collected. 在您的情况下,在first = first.next ,Java GC将识别到first指向的旧节点现在不可访问,因此可以进行收集。

Let's say our Node looks like this 假设我们的Node看起来像这样

private class Node{
Item item;
Node next;
}

You don't have to assign null to first.item. 您不必为first.item分配null。 When assigning first = first.next;, the first.next is a Node, which means it has both Item and the next Node. 当分配first = first.next;时,first.next是一个Node,这意味着它同时具有Item和下一个Node。

Loitering is, holding a reference to an object when it is no longer needed. 游荡是在不再需要对象时保留对其的引用。 In your case you renew the reference, pointing to the next Item in the stack. 在您的情况下,您可以续订引用,指向堆栈中的下一个项目。

However, if we would use an array, our code would be: 但是,如果我们使用数组,我们的代码将是:

public Item pop() {
return arrayItems[--N];
}

Here, we return an Item from the stack, but the pointer remains, pointing to the element we took of the stack. 在这里,我们从堆栈中返回一个Item,但是指针仍然保留,指向我们从堆栈中获取的元素。 To avoid loitering, we set removed item entry to null: 为了避免闲逛,我们将移除的项目条目设置为null:

public Item pop() {
Item item = arrayItems[--N];
arrayItems[N] = null;
return item;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM