Thursday 26 July 2012

Copying data from one ArrayList to another ArrayList in Java


Many a times you need to create a copy of ArrayList for this purpose you can use addAll(Collection c) method of ArrayList in Java to copy all elements from on ArrayList to another ArrayList in Java.

The complete source code is given below:


import java.util.ArrayList;

public class CopyFromOneArrayListToAnotherArrayListExample {

 public static void main(String[] args) {

  // create an ArrayList object
  ArrayList arrayList = new ArrayList();

  // Add elements to Arraylist

  arrayList.add("1");
  arrayList.add("2");
  arrayList.add("3");

  System.out.println("Original Arraylist contains : ");

  for (Object e : arrayList) {

   System.out.println(e);
  }

  // create an ArrayList object for copying.

  ArrayList arrayListCopy = new ArrayList();

  /**
   * Appends all of the elements in the specified Collection to the end of
   * this list, in the order that they are returned by the specified
   * Collection's Iterator.
   **/

  arrayListCopy.addAll(arrayList);

  System.out.println("Copied Arraylist contains : ");

  for (Object e : arrayListCopy) {

   System.out.println(e);
  }

 }

}


The output is:



Original Arraylist contains :
1
2
3
Copied Arraylist contains :
1
2
3

No comments:

Post a Comment