简体   繁体   English

将ArrayList中的对象设置为null

[英]Setting objects in an ArrayList to null

If I was to have an ArrayList of objects, and I set a few of them to null, are they susceptible to gc? 如果我要拥有一个ArrayList对象,并且将其中一些对象设置为null,那么它们是否容易受gc影响? Or will they stay since they are still being referenced by the ArrayList 否则它们会留下来,因为它们仍被ArrayList引用

ex: 例如:

for(NPC n : NPCs){
    n.act();
    n.draw(frame);
    if(n == outOfMap){
            n = null;
        }

}

If that loop is "always" being iterated over, will the outOfMap objects be collected? 如果该循环“总是”被迭代,是否将收集outOfMap对象? or simply stay there will a null value? 还是只是呆在那里会有一个空值?

You need to distinguish between objects and references to them. 您需要区分对象和对其的引用。 For the same one object, multiple references could point to it. 对于同一个对象,可以引用多个引用。 When the number of references reaches 0, the object is a candidate to be removed by the garbage collector. 当引用数达到0时,该对象就是要由垃圾回收器删除的候选对象。

In this loop: 在此循环中:

for(NFC n : NFCs)
{
   n = null;
}

The n reference is different than the reference the ArrayList uses to track the object in the list, so setting n to null reduces the references to the object down by one, but it leaves the reference from the ArrayList to the object intact and as such, the object is not a candidate for garbage collection. n引用不同于ArrayList用来跟踪列表中对象的引用,因此将n设置为null会使对对象的引用减少一,但是它完整地保留了从ArrayList到对象的引用,因此,该对象不是垃圾回收的候选对象。 You should use the remove method to remove the object from the ArrayList. 您应该使用remove方法从ArrayList中删除对象。 At that point, if no other references to the object exist elsewhere, it'll be a candidate for removal. 到那时,如果其他地方没有对该对象的其他引用,则它将成为删除对象的候选对象。

You're confused I think between variables and objects. 我认为您在变量和对象之间感到困惑。 If a variable references null, there's nothing to GC since variables aren't GC'd, objects are. 如果变量引用了null,则GC没有任何作用,因为变量不是GC,对象是GC。 The ArrayList won't be GC'd if there's a valid reference to it, and if it contains nulls, then there's nothing in it to be held in memory or to GC. 如果存在对ArrayList的有效引用,并且该数组列表包含空值,则不会对它进行GC处理,因此其中没有任何内容可以保存在内存或GC中。

If on the other hand, the ArrayList contains objects, and then later you null an item or two, then it's not the ArrayList that will determine the GC-ability of the object since its reference to it has been severed, but whether or not other objects reference them. 另一方面,如果ArrayList包含对象,然后您将一个或两个项目设为空,则不是由ArrayList决定对象的GC能力,因为对它的引用已被切断,而是是否其他对象引用它们。

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

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