How To Shallow Copy Or Clone a ArrayList

 

How To Shallow Copy Or Clone  a ArrayList

Here we are creating duplicate object of an ArrayList instance . clone() Returns a shallow copy of this ArrayList instance.

import java.util.ArrayList;

public class CloneOfArrayList {

public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
// add element in arraylist
arr.add(“c”);
arr.add(“php”);
arr.add(“html”);
arr.add(“java“);
// print arraylist
System.out.println(“arrayList is = ” + arr);

//Returns a shallow copy of this ArrayList instance
ArrayList<String> clone1 = (ArrayList<String>) arr.clone();
System.out.println(“Clone is=”+clone1);
}

}

Output:

arrayList is = [c, php, html, java]

Clone is=[c, php, html, java

 

Related Posts:


Notice: compact(): Undefined variable: limits in /home/javaprof/public_html/wp-includes/class-wp-comment-query.php on line 853

Notice: compact(): Undefined variable: groupby in /home/javaprof/public_html/wp-includes/class-wp-comment-query.php on line 853

Leave a Reply

Your email address will not be published. Required fields are marked *

− 1 = 2