views:

251

answers:

4

Below is the code

ArrayList arList = someMethod();// returning ArrayList with customDO objects

Now somewhere in different class I am getting data from this arList

CustomDo custDO= (CustomDO)arList.get(0);

Will the arList be alive as long as custDO is alive ? If yes, will below piece of code help

CustomDO custDO = ((CustomDO)arList.get(0)).cloneMe();
// where cloneMe has defintion as return ((CustomDO)super.clone());
// CustomDo implements Cloneable

Is there a better way to keep a copy of only the first element of arList and discard the list so that it can be collected by garbage collector ?

+3  A: 

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 ?

You don't have to make a copy of the list element. As long as you have another reference to it, it will not be garbage-collected, even if the list you got it from is. And the list will be garbage-collected as soon as you remove all references to it.

There is no need in Java to clone anything just to make sure that the object does not disappear. In Java a reference to an object is always valid. It cannot happen that the data for a live reference gets invalid.

You only want to make a copy (clone) if you are afraid that other people who reference the same object might change its contents (calling some setter on it) in ways that would cause trouble for you (or you want to have a private copy to change it without affecting others).

Thilo
I intend to remove the list from the memory and keep only the first elment alive. How can this be achieved ?
Ravi Gupta
No problem, just do what you do now. Your custDo reference will remain valid, even after the list is long gone.
Thilo
It will not be garbage collected until there are no more references to the list. Set any reference to your list to null or allow them to disappear via returning from the method where the reference is declared. Once there are no more references to the list then it will be free to be garbage collected. Your first element will stay alive because I assume that you will be keeping a reference to it.
rayd09
Thanks Thilo/ray. Now I know
Ravi Gupta
A: 
// reference to first object
CustomDO custDO = ((CustomDO)arList.get(0));
// let arList be garbage collected
arList = null;

Another thing you should know is that Collections clone() methods do a shallow (flat) copy. Sometimes you need to have deep copies (to allow modifing them independedly)

stacker
A: 

As long as you have access to CustomDO custDO object, it will not be garbage collected. The list can be garbage collected if there is no reference to it.

fastcodejava
A: 

The ArrayList is an ordinary Object, and only references to this object will keep the list alive. Of course, as long as the list is alive, all its elements are also alive, but the converse does not hold.

mfx