.clone()
Anonymous contributor
Published Jun 24, 2024
Contribute to Docs
In Java, the .clone()
method returns a cloned version of the given ArrayList
. The cloned version is a shallow copy containing references to all the elements in the original ArrayList
, not the elements themselves.
Syntax
arrayList.clone();
arrayList
: TheArrayList
to be cloned.
Example
The following example illustrates how to use the .clone()
method.
import java.util.ArrayList;class Main {public static void main(String[] args) {// Creating an ArrayListArrayList<Integer> nums = new ArrayList<>();// Adding elements to the ArrayListnums.add(12);nums.add(34);nums.add(56);// Printing the ArrayListSystem.out.println("Original ArrayList: " + nums);// Cloning the ArrayListArrayList<Integer> clonedNums = (ArrayList<Integer>)nums.clone();// Printing the cloned ArrayListSystem.out.println("Cloned ArrayList: " + clonedNums);}}
Since the .clone()
method returns an Object
, it needs to be cast to ArrayList<Integer>
to convert it into an ArrayList
of integers.
The above example produces the following output:
Original ArrayList: [12, 34, 56]Cloned ArrayList: [12, 34, 56]
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.