In this tutorial, we will see examples of ArrayList clone()
method. This method creates a shallow copy of an ArrayList.
Syntax:
newList = oldList.clone()
Creates a shallow copy of oldList
and assign it to newList
.
Example 1: Creating a copy of an ArrayList using clone()
In this example, we have an ArrayList of String type and we are cloning it to another ArrayList using clone()
method. The interesting point to note here is that when we added and removed few elements from original ArrayList al
after the clone()
method, the another ArrayList al2
didn’t get affected. It shows that clone() method just returns a shallow copy of ArrayList.
import java.util.ArrayList; public class Details { public static void main(String a[]){ ArrayList<String> al = new ArrayList<String>(); //Adding elements to the ArrayList al.add("Apple"); al.add("Orange"); al.add("Mango"); al.add("Grapes"); System.out.println("ArrayList: "+al); ArrayList<String> al2 = (ArrayList<String>)al.clone(); System.out.println("Shallow copy of ArrayList: "+ al2); //add and remove from original ArrayList al.add("Fig"); al.remove("Orange"); //print both ArrayLists after add & remove System.out.println("Original ArrayList:"+al); System.out.println("Cloned ArrayList:"+al2); } }
Output:
ArrayList: [Apple, Orange, Mango, Grapes] Shallow copy of ArrayList: [Apple, Orange, Mango, Grapes] Original ArrayList:[Apple, Mango, Grapes, Fig] Cloned ArrayList:[Apple, Orange, Mango, Grapes]
Example 2: Clone Integer ArrayList
In the following example, we are creating a shallow copy of an Integer ArrayList using clone() method. This example is similar to the first example, except that here list contains integers.
import java.util.ArrayList; public class JavaExample { public static void main(String args[]) { // Creating an ArrayList ArrayList<Integer> numbers = new ArrayList<Integer>(); // Adding elements to the arraylist numbers.add(3); numbers.add(7); numbers.add(5); numbers.add(11); numbers.add(9); // print first ArrayList System.out.println("Original ArrayList: "+ numbers); // Creating another ArrayList // Copying the array list "numbers" to this list ArrayList<Integer> copyList = (ArrayList<Integer>)numbers.clone(); // Displaying the other linked list System.out.println("Second ArrayList: "+ copyList); } }
Output:
Original ArrayList: [3, 7, 5, 11, 9] Second ArrayList: [3, 7, 5, 11, 9]
reshma says
Hello sir…The clone program doesn’t compile at all…
when complied..It says..
“Note: Java uses unchecked or unsafe operation ”
” Note: recompile with -Xlint: unchecked for details ”
What could be the meaning of this ..How can I rectify it???