CodesJava

Easy learning with example program codes

how to copy or clone a arraylist in java?


ArrayList:

ArrayList class extends AbstractList and implements the List interface. It uses dynamic arrays for storing elements. It maintains insertion order. ArrayList can contain duplicate elements. It is not synchronized.

Note: ArrayList provides the facility of random access because of it is index based.

The clone() method is used to copy or clone a arraylist in java.

Example:

package com.codesjava;
 
import java.util.ArrayList;
 
public class Test {
  public static void main(String args[]){
	ArrayList<String> list = new ArrayList<String>();
	list.add("Jai");
	list.add("Mahesh");
	list.add("Vivek");
	list.add("Naren");
	list.add("Hemant");
	list.add("Vishal");
	System.out.println("Actual ArrayList:"+list);
	ArrayList<String> copy = (ArrayList<String>) list.clone();
        System.out.println("Cloned ArrayList:"+copy);
  }
}

Output

Actual ArrayList:[Jai, Mahesh, Vivek, Naren, Hemant, Vishal]
Cloned ArrayList:[Jai, Mahesh, Vivek, Naren, Hemant, Vishal]


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap