如果有一个引用它的字段,元素是否会被垃圾收集? [英] Will an element be garbage collected if there is a reference to its field?
本文介绍了如果有一个引用它的字段,元素是否会被垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A {
public String s;
}
和
A a1 = new A();
a1.s =bla;
A a2 = new A();
2.s = a1.s;
a1 = null;
a1.s
允许它被收集(并且我宁愿做一个深层复制, a2.s = new String(a1.s)
非常感谢!
解决方案如果
对象
持有另一个对象
的引用,并且当您设置容器对象的引用 null
,子或包含 object
自动变为垃圾回收的资格。 有关更多信息,请参阅此链接。
I.e., in
class A {
public String s;
}
and
A a1 = new A();
a1.s = "bla";
A a2 = new A();
a2.s = a1.s;
a1 = null;
will a1
be garbage collected or is the reference to a1.s
permitting it from being collected (and I should rather do a deep copy, a2.s = new String(a1.s)
)?
Thanks a lot in advance!
解决方案
If an object
holds a reference of another object
and when you set container object's reference null
, child or contained object
automatically becomes eligible for garbage collection.
See this link for further information.
这篇关于如果有一个引用它的字段,元素是否会被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文