Copy one list to another with copy()


The Collections.copy() method takes two list objects as parameters. The first one is the destination list and the second is the source list. The source list elements are copied into target list. Here, copy operation does actually replacement.

Following is the method signature

  • static void copy(List destination1, List source1): Copies all the elements of List source1 into the destination1 list. It is like arraycopy() method.
Example on Copy one list to another with copy()
import java.util.*;
public class CollectionsCopy
{
  public static void main(String args[])
  {
    ArrayList firstList = new ArrayList();
    firstList.add(50);
    firstList.add(10);
    firstList.add(20);
    System.out.println("Elements firstList: " + firstList);

    ArrayList secondList = new ArrayList();
    secondList.add("one");
    secondList.add("two");
    secondList.add("three");
    System.out.println("Elements secondList: " + secondList);

    Collections.copy(secondList, firstList);
    System.out.println("Elements of secondList after copying firstList: " + secondList); 

    ArrayList thirdList = new ArrayList();
    thirdList.add("one");
    thirdList.add("two");
    thirdList.add("three");
    thirdList.add("four");
    thirdList.add("five");
    System.out.println("\nElements thirdList: " + thirdList);

    Collections.copy(thirdList, firstList);
    System.out.println("Elements of thirdList after copying firstList: " + thirdList); 
  }
}


Copy one list to another with copy()
Output screen on Copy one list to another with copy()

ArrayList firstList = new ArrayList();
firstList.add(50); firstList.add(10); firstList.add(20);

ArrayList object firstList is created with three elements 50, 10 and 20.

ArrayList secondList = new ArrayList();
secondList.add(“one”); secondList.add(“two”); secondList.add(“three”);

Another ArrayList object secondList is created with three elements "one", "two" and "three".

Collections.copy(secondList, firstList);

In the above statement the destination list is secondList and the source list is firstList. The firstList elements are copied into secondList. Infact, all the three elements of secondList are replaced by the three elements of firstList. Observe the screenshot. Both includes three elements. Here the size of both lists is same.

Let us see another combination.

ArrayList thirdList = new ArrayList();
thirdList.add(“one”);

An ArrayList object thirdList with five elements is created – "one", "two", "three", "four" and "five".

Collections.copy(thirdList, firstList);

Now fisrtList elements are copied into thirdList. Remember, the firstList contains three elements. The first three elements of thirdList are replaced and the next two remains same (not replaced). Observe the output.

Note: If the source list is bigger than the destination list, the JVM throws IndexOutOfBoundsException.

Leave a Comment

Your email address will not be published.