Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying List of objects by value in Java

I have a class that gets in its constructor a list of objects, List<Object>. Each time the list could be made out of elements from a different type. It's something generic, and I don't know what their class type will be.

I want to save my self a copy of that list, before letting the user change its values. But since the copy is done by reference, both lists (original and copy) are being changed...

How can I copy my list by value?

like image 513
Dvora Avatar asked May 08 '12 09:05

Dvora


People also ask

How do you copy all the elements of a list to another in Java?

To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list. Approach: Create a cloneable class, which has the clone method overridden. Create a list of the class objects from an array using the asList method.

How do you copy an ArrayList?

The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone(); Return Value: This function returns a copy of the instance of Object.


1 Answers

Your question is not clear.

  • If you want a shallow copy (i.e. a copy of the list that will contain references to the objects in the original list, then the clone method will do the job, as will a copy constructor on a List implementation class.

  • If you want a deep copy (i.e. a copy of the list containing copies of the original objects) then your best bet is to create a new list and populate it with clones of the original list elements. However, there is a catch. The clone method is not provided by default. A lot of common utility classes are cloneable, by custom classes are not ... unless you've implemented it. If your list contains any non-cloneable object, you will get exceptions at runtime.

There are other deep-copying alternatives to clone, but just like cloning they don't work with all classes. And really, that's the crux of the problem if your solution has to be generic.

like image 157
Stephen C Avatar answered Oct 20 '22 16:10

Stephen C