Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clone a generic List in Java?

People also ask

Can I clone an ArrayList in Java?

ArrayList clone() method in Java with Examplesclone() method is used to create a shallow copy of the mentioned array list. It just creates a copy of the list. Parameters: This method does not take any parameters. Return Value: This function returns a copy of the instance of Linked list.

How do you make a deep copy of a list in Java?

To create a deep copy of the class, divide all the class members into two categories of mutable and immutable types. All immutable field members can be used as it is.

How do I create a list from one list to another in Java?

Another approach to copying elements is using the addAll method: List<Integer> copy = new ArrayList<>(); copy. addAll(list); It's important to keep in mind whenever using this method that, as with the constructor, the contents of both lists will reference the same objects.


Why would you want to clone? Creating a new list usually makes more sense.

List<String> strs;
...
List<String> newStrs = new ArrayList<>(strs);

Job done.


ArrayList newArrayList = (ArrayList) oldArrayList.clone();

This is the code I use for that:

ArrayList copy = new ArrayList (original.size());
Collections.copy(copy, original);

Hope is usefull for you


Be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.