In the previous article we have discussed about Java ArrayList clear() Method with Example
In this article we are going to see the use ArrayList clone() method in Java along with suitable examples.
Java ArrayList clone() Method with Example
clone( ):
This java.util.ArrayList.clone()
method is used to make copy of all the elements of the same arraylist.
It return the same value as it copy all the elements from the ArrayList and makes a clone.
Syntax:
arrayListName.clone()
Where,
arrayListName
refers to the name of your ArrayList.
Let’s see different examples to understand it more clearly.
Method-1: Java ArrayList clone() Method – Example with String Type ArrayList
Approach:
- Create a new ArrayList of type String.
- Add string elements into the ArrayList using the add() method.
- Display the ArrayList elements
- Clone the same ArrayList using
clone( )
method. - Print the cloned ArrayList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create an ArrayList of String datatype ArrayList<String> arr = new ArrayList<String>(); // Adding some elements to the ArrayList arr.add("ram"); arr.add("shyam"); arr.add("gyan"); arr.add("dhyan"); arr.add("vyan"); // Prints the ArrayList elements System.out.println("The elements of ArrayList are: "+arr); // cloning the same above arrayList ArrayList<String> clone = (ArrayList<String>)arr.clone(); System.out.println("Cloned ArrayList: " + clone); } }
Output: The elements of ArrayList are: [ram, shyam, gyan, dhyan, vyan] Cloned ArrayList: [ram, shyam, gyan, dhyan, vyan]
Method-2: Java ArrayList clone() Method – Example with Integer Type ArrayList
Approach:
- Create a new ArrayList of type Integer.
- Add Integer elements into the ArrayList using the add() method.
- Display the ArrayList elements
- Clone the same ArrayList using
clone( )
method. - Print the cloned ArrayList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create an ArrayList of Integer datatype ArrayList<Integer> arr = new ArrayList<Integer>(); // Adding some elements to the ArrayList arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); // Prints the ArrayList elements System.out.println("The elements of ArrayList are: "+arr); // cloning the same above arrayList ArrayList<Integer> clone = (ArrayList<Integer>)arr.clone(); System.out.println("Cloned ArrayList: " + clone); } }
Output: The elements of ArrayList are: [1, 2, 3, 4, 5] Cloned ArrayList: [1, 2, 3, 4, 5]
The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.
Related Java Programs: