Skip to Content

Append all elements of other Collection to Java ArrayList Example

  1. /*
  2.   Append all elements of other Collection to Java ArrayList Example
  3.   This Java Example shows how to append all elements of other Collection object
  4.   at the end of Java ArrayList object using addAll method. This program shows
  5.   how to append all elements of Java Vector to Java ArrayList object.
  6. */
  7.  
  8. import java.util.ArrayList;
  9. import java.util.Vector;
  10.  
  11. public class AppendAllElementsOfOtherCollectionToArrayListExample {
  12.  
  13.   public static void main(String[] args) {
  14.  
  15.     //create an ArrayList object
  16.     ArrayList arrayList = new ArrayList();
  17.    
  18.     //Add elements to Arraylist
  19.     arrayList.add("1");
  20.     arrayList.add("2");
  21.     arrayList.add("3");
  22.    
  23.     //create a new Vector object
  24.     Vector v = new Vector();
  25.     v.add("4");
  26.     v.add("5");
  27.    
  28.     /*
  29.       To append all elements of another Collection to ArrayList use
  30.       boolean addAll(Collection c) method.
  31.       It returns true if the ArrayList was changed by the method call.
  32.     */
  33.    
  34.     //append all elements of Vector to ArrayList
  35.     arrayList.addAll(v);
  36.    
  37.     //display elements of ArrayList
  38.     System.out.println("After appending all elements of Vector,
  39.                              ArrayList contains..");
  40.     for(int i=0; i<arrayList.size(); i++)
  41.       System.out.println(arrayList.get(i));
  42.  
  43.   }
  44. }
  45.  
  46. /*
  47. Output would be
  48. After appending all elements of Vector, ArrayList contains..
  49. 1
  50. 2
  51. 3
  52. 4
  53. 5
  54. */