English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList clone() method generates a shallow copy of ArrayList.
Here, shallow copy means it will create a copy of the arraylist object.
The syntax of the clone() method is:
arraylist.clone()
The clone() method has no parameters.
Return a copy of the ArrayList object
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create an ArrayList ArrayList<Integer> number = new ArrayList<>(); number.add(1); number.add(3); number.add(5); System.out.println("ArrayList: ", + number); // Create a copy of number ArrayList<Integer> cloneNumber = (ArrayList<Integer>)number.clone(); System.out.println("ArrayList copy: ", + cloneNumber); } }
Output Result
ArrayList: [1, 3, 5] ArrayList copy: [1, 3, 5]
In the above example, we created an arraylist named number. Note the expression
(ArrayList<Integer>)number.clone()
Here,
number.clone() - Return a copy of the object number
(ArrayList<Integer>) - Convert the clone() return value to an Integer type arraylist (For more information, please visitJava Type Conversion)
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create an ArrayList ArrayList<Integer> prime = new ArrayList<>(); prime.add(2); prime.add(3); prime.add(5); System.out.println("Prime numbers: " + prime); //Print clone() return value System.out.println("clone() return value: " + prime.clone()); } }
Output Result
Prime numbers: [2, 3, 5] clone() return value: [2, 3, 5]
In the above example, we created an ArrayList named prime. Here, we printed the value returned by clone().
Note: The clone() method is not specific to the ArrayList class. Any class that implements the Clonable interface can use the clone() method.