Possible Duplicate:
How to clone ArrayList and also clone its contents?
I have a ArrayList<Widget>
that I would like to "deep" clone so that making modifications to any items in the original list does not have any effect on the items in the cloned list:
ArrayList<Widget> origList = getMyList();
ArrayList<Widget> cloneList = origList.clone();
// Remove the 5th Widget from the origina list
origList.remove(4);
// However, the cloneList still has the 5th Widget and is unchanged
// Change the id of the first widget
origList.get(0).setId(20);
// However in cloneList, the 1st Widget's ID is not 20
What's the best/safest way of accomplishing this? I imagine that it's not as simple as:
ArrayList<Widget> cloneList = origList.clone();
I imagine the fact that this is a built-in ArrayList
type, plus the fact that its generic, are going to complicate things. I also imagine I will need to write a special clone()
override for my Widget
class?
Thanks in advance!
Edit:
I'd also be completely receptive if there is a commons JAR out there that does this heavy lifting for me, so please feel free to make suggestions, however I would still like to know how to do this the ole' fashion way so I can learn ;-)