2

我在 Java 中使用下面的代码从链表中删除重复数据,我的问题是明确设置 current.next = null 对我来说是否是个好主意,即当前将是重复数据,所以我设置了前一个节点的在当前的下一个但要在java中删除的当前旁边意味着使其可用于gc。那么,我真的需要明确设置它吗?

public void removeDuplicates()
{
    HashSet<Integer> nodeSet = new HashSet<Integer>();
    Node previous = this;
    Node current = previous;
    while(current!=null)
    {
         if(!nodeSet.contains(current.data))
         {
             nodeSet.add(current.data);
             previous = current;
             current = current.next;
         }
        else
         {
             previous.next = current.next;
             current.next = null;
             current = previous.next;

         }
    }

}
4

5 回答 5

2

As soon as current becomes unreachable, it will make zero difference what objects are reachable from it. So no, this is not necessary.

于 2012-07-17T20:41:17.977 回答
2

如果您的节点无法访问,那么它的next节点也将无法访问(假设它只有 1 个父节点)

于 2012-07-17T20:39:36.900 回答
1

Nope! You hit the nail on the head. The set to null of current is overwritten anyway when you set its value on the next run through. Since you only care about 'current' when it has a value hen you don't need to worry about setting it to null when you aren't using it. The GC will do its job when the method (and its variables) go out of scope.

于 2012-07-17T20:41:19.953 回答
0

That shouldn't have a negative effect, no.

于 2012-07-17T20:40:46.930 回答
0

有时由标准库代码本身执行此操作的原因是,“如果一个对象没有被任何其他对象指向,它将在下一个 GC 步骤中被收集”的基本假设在现代 JVM 上是错误的.

一旦current节点在老年代,它的下一个指针将被认为是年轻 GC 运行的根集的一部分,这反过来意味着这可能会导致几个同样从列表中删除的年轻节点也不会被收集,这意味着他们也进入了老一代。最后,这可能会导致更大的老年代、更多的根指针和更少的对象在年轻 GC 中被收集——所有这些都是坏事。

好吧,这就是最终的理论,一些非常聪明的人将其归结为,效果是否真的很明显是另一回事 - 没有对此进行任何测试。

于 2012-07-17T21:47:58.177 回答