这个java对象是否有资格在List中进行垃圾收集 [英] Is this java Object eligible for garbage collection in List

查看:36
本文介绍了这个java对象是否有资格在List中进行垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

所以在上面的场景中,我创建了很多 Boss 对象,然后取消引用它们(我知道我不需要写b = null",但我这样做是为了清楚我的问题).在正常情况下,我会通过这样做将它们标记为垃圾收集,但是因为在这种情况下,我将这些 Boss 对象添加到 List 集合中,它们是否标记为 GC?如果不是,那为什么?以及 List 收集在内部如何工作以保存每个添加的 Object 的引用,从而避免垃圾收集?

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] 

问题的范围仅限于在for循环中创建的单个Boss对象,考虑到该方法将List的引用返回给外界.

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 在内部具有 Object[] elementData.当您将 b 添加到 bossList ArrayList 时,分配了 elementData[0] = b.因此,当您将 null 分配给 b 时,Boss 的实例仍然是从 elementData[0] 引用的,并且不能被引用GCed.但是由于 ArrayList 实例仅在方法返回 ArrayListBoss 实例后才从方法的变量中引用,因此将有资格进行 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对象是否有资格在List中进行垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆