Skip to Content

Copy Elements of One Java ArrayList to Another Java ArrayList Example

  1. /*
  2.   Copy Elements of One Java ArrayList to Another Java ArrayList Example
  3.   This java example shows how to copy all elements of one Java ArrayList object to
  4.   another Java ArrayList object using copy method of Collections class.
  5. */
  6.  
  7. import java.util.ArrayList;
  8. import java.util.Collections;
  9.  
  10. public class CopyElementsOfArrayListToArrayListExample {
  11.  
  12.   public static void main(String[] args) {
  13.      
  14.     //create first ArrayList object
  15.     ArrayList arrayList1 = new ArrayList();
  16.    
  17.     //Add elements to ArrayList
  18.     arrayList1.add("1");
  19.     arrayList1.add("2");
  20.     arrayList1.add("3");
  21.    
  22.     //create another ArrayList object
  23.     ArrayList arrayList2 = new ArrayList();
  24.    
  25.     //Add elements to Arraylist
  26.     arrayList2.add("One");
  27.     arrayList2.add("Two");
  28.     arrayList2.add("Three");
  29.     arrayList2.add("Four");
  30.     arrayList2.add("Five");
  31.    
  32.     /*
  33.       To copy elements of one Java ArrayList to another use,
  34.       static void copy(List dstList, List sourceList) method of Collections class.
  35.      
  36.       This method copies all elements of source list to destination list. After copy
  37.       index of the elements in both source and destination lists would be identical.
  38.      
  39.       The destination list must be long enough to hold all copied elements. If it is
  40.       longer than that, the rest of the destination list's elments would remain
  41.       unaffected.      
  42.     */
  43.    
  44.     System.out.println("Before copy, Second ArrayList Contains : " + arrayList2);
  45.    
  46.     //copy all elements of ArrayList to another ArrayList using copy
  47.     //method of Collections class
  48.     Collections.copy(arrayList2,arrayList1);
  49.    
  50.     /*
  51.       Please note that, If destination ArrayList object is not long
  52.       enough to hold all elements of source ArrayList,
  53.       it throws IndexOutOfBoundsException.
  54.     */
  55.  
  56.     System.out.println("After copy, Second ArrayList Contains : " + arrayList2);  
  57.   }
  58. }
  59.  
  60. /*
  61. Output would be
  62. Before copy, Second ArrayList Contains : [One, Two, Three, Four, Five]
  63. After copy, Second ArrayList Contains : [1, 2, 3, Four, Five]
  64. */