Skip to content
Advertisement

How to clone ArrayList and also clone its contents?

How can I clone an ArrayList and also clone its items in Java?

For example I have:

JavaScript

And I would expect that objects in clonedList are not the same as in dogs list.

Advertisement

Answer

You will need to iterate on the items, and clone them one by one, putting the clones in your result array as you go.

JavaScript

For that to work, obviously, you will have to get your Dog class to implement the Cloneable interface and override the clone() method.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement