21 Sept 2012

Append all elements of other Collection to Java ArrayList

/* append all elements of other collection to java arraylist example */

import java.util.ArrayList;
import java.util.Vector;

public class AppendCollectionToArrayListExample 
{
  public static void main(String[] args) 
  {
    //create an ArrayList object
    
java.util.ArrayList arrayList = new java.util.ArrayList();
  
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
  
    //create a new Vector object
    
java.util.Vector v = new java.util.Vector();
    v.add("4");
    v.add("5");
  
    /*
      boolean addAll(
java.util.Collection c) method.
    */
  
    //append all elements of Vector to ArrayList
    arrayList.addAll(v);
  
 System.out.println("After appending all elements of Vector,ArrayList contains..");
    for(int i=0; i<arrayList.size(); i++)
      System.out.println(arrayList.get(i));

  }
}

Output:
After appending all elements of Vector, ArrayList contains..
1
2
3
4
5

0 comments:

Post a Comment