本文介绍了这是Java对象资格在列表垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要问可能是一个愚蠢的问题,所以请原谅我的。
因此,它是这样的:

What I am asking might be a stupid question so please pardon me for that.So it goes like this :

List<Boss> bossList = new ArrayList<Boss>();
Boss b = null;
for(Employee e : List<Employee> myList){
    b = new Boss();
    b.setEmployee(e);
    bossList.add(b);
    b = null;
}

因此​​,在上述情况下,我创造很多老板对象,然后去引用它们(我知道我不需要写B =空,但我做到了我的问题的清晰)。在正常情况下,我会打上他们垃圾收集,由doeing这一点,但因为在这种情况下,我列出集合中添加这些老板的对象,他们被标记为GC或不?如果没有,那么为什么呢?以及如何做列表征管工作内部持有引用的每个对象增加,从而避免垃圾收集?

So in above scenario, I am creating lot of Boss objects and then de-referencing them(I know I don't need to write "b = null", but i did it for clarity of my question). In normal scenario, I would have marked them to garbage collection, by doeing this, but because in this scenario, I am adding those Boss objects in List collection, are they marked for GC or not? If not then why? And how does List collection work internally to hold references for each Object added, so as to avoid garbage collection?

[EDIT] 

问题的范围仅限于对环路创建的个体老板对象,认为此方法返回列表对外界的参考。

The scope of question is only limited to the individual Boss objects created in for loop, considering that this method returns the reference of the List to the outside world.

推荐答案

ArrayList中有对象[] elementData中内部。当您添加 B bossList ArrayList的分配 elementData中[0] = B 。所以,当你分配 B 老大的实例还是从引用从elementData [0] ,不能GCed。但是,由于的ArrayList 实例只从方法的变量的方法同时返回的ArrayList 老大后参考情况下,将有资格获得GC。

ArrayList has Object[] elementData internally. When you added b to bossList ArrayList assigned elementData[0] = b. So when you assigned null to b the instance of Boss is still referenced from elementData[0] and cannot be GCed. But since ArrayList instance is referenced only from method's variable after the method returns both ArrayList and Boss instances will be eligible for GC.

这篇关于这是Java对象资格在列表垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 23:37