下面是代码
ArrayList arList = someMethod();// returning ArrayList with customDO objects
现在在不同类(class)的某个地方,我正在从这个 arList 获取数据
CustomDo custDO= (CustomDO)arList.get(0);
只要 custDO 还活着,arList 就会一直活着吗?如果是,下面的代码会有帮助
CustomDO custDO = ((CustomDO)arList.get(0)).cloneMe();
// where cloneMe has defintion as return ((CustomDO)super.clone());
// CustomDo implements Cloneable
是否有更好的方法来仅保留 arList 第一个元素的副本并丢弃该列表,以便垃圾收集器可以收集它?
最佳答案
Is there a better to keep a copy of only the first element of arList and discard the list so that it can be collected by garbage collector ?
您不必复制列表元素。只要您有另一个对它的引用,它就不会被垃圾收集,即使您从中获取它的列表也是如此。一旦您删除对列表的所有引用,该列表就会被垃圾收集。
在 Java 中,不需要克隆任何东西来确保对象不会消失。在 Java 中,对对象的引用始终有效。实时引用的数据不会失效。
如果您担心引用同一对象的其他人可能会以会给您带来麻烦的方式更改其内容(调用其上的某些 setter )(或者您希望有一个私有(private)副本来更改它而不影响其他人)。
关于java - java中对象引用和克隆是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2107231/