Friday, 30 May 2014

ArrayList : addAll(Collection c) : Add Collection Of Data

public boolean addAll(Collection<? extends E> c)
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.

import java.util.*;

class ArrayListAddAll{
 public static void main(String args[]){
  ArrayList<Integer> myList = new ArrayList<> ();
  Set<Integer> mySet =new HashSet<> ();
  
  /* Add Elements to myList */
  for(int i=0; i < 10; i++){
   myList.add(i);
  }
  
  /* Add Elements to mySet */
  for(int i=5; i < 15; i++){
   mySet.add(i);
  }
  
  System.out.println("Elements in myList are ");
  System.out.println(myList +"\n");
  System.out.println("Elements in mySet are ");
  System.out.println(mySet +"\n");
  
  /* Add mySet Data to myList */
  myList.addAll(mySet);
  
  System.out.println("Elements in myList after adding mySet are");
  System.out.println(myList); 
 }
}

Output
Elements in myList are
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Elements in mySet are
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Elements in myList after adding mySet are
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

1. Throws NullPointerException if the specified collection is null
import java.util.*;

class ArrayListAddAllNullPointer{
 public static void main(String args[]){
  ArrayList<Integer> myList = new ArrayList<> ();
  Set<Integer> mySet =null;
  
  /* Add Elements to myList */
  for(int i=0; i < 10; i++){
   myList.add(i);
  }
  
  System.out.println("Elements in myList are ");
  System.out.println(myList +"\n");
  System.out.println("Elements in mySet are ");
  System.out.println(mySet +"\n");
  
  System.out.println("Add mySet Data to myList");
  /* Add mySet Data to myList */
  myList.addAll(mySet);
  
  System.out.println("Elements in myList after adding mySet are");
  System.out.println(myList); 
 }
}

Output
Elements in myList are
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Elements in mySet are
null

Add mySet Data to myList
Exception in thread "main" java.lang.NullPointerException
        at java.util.ArrayList.addAll(ArrayList.java:530)
        at ArrayListAddAllNullPointer.main(ArrayListAddAllNullPointer.java:20)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment