In this tutorial we will learn how to clone an ArrayList
to another one. We would be using clone() method of ArrayList class to serve our purpose.
Object clone()
This method returns a shallow copy of the ArrayList instance.
Complete example of ArrayList Cloning
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 see here is when we added and removed few elements from original ArrayList after the clone() method, the cloned ArrayList didn’t get affected. It shows that clone() method just returns a shallow copy of ArrayList.
package beginnersbook.com; 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 on original ArrayList al.add("Fig"); al.remove("Orange"); //Display of 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]
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???