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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With