If you want to clone ArrayList and also clone its contents? You will need to iterate on the items, and clone them one by one, putting the clones in your result array as you go.
1 2 3 4 5 | public static List<Dog> cloneList(List<Dog> list) { List<Dog> clone = new ArrayList<Dog>(list.size()); for (Dog item : list) clone.add(item.clone()); return clone; } |
For that to work, obviously, you will have to get your Dog class to implement the Cloneable
interface and override the clone()
method.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.