Search code examples
javalistgenericsclone

Cloning lists in Java


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


Solution

  • This is a non-trivial task, I suggest you use one of the available libraries such as http://code.google.com/p/cloning/

    See also: Java: recommended solution for deep cloning/copying an instance

    If you want to see how it's done get an open-source library and look at the source :)