Tuesday, 1 April 2014

addAll : Add Collection of Elements

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 ListAddAll{
 public static void main(String args[]){
  List<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 UnsupportedOperationException if the addAll operation is not supported by this list
import java.util.*;
class ListAddAllUnsupported{
 public static void main(String args[]){
  List<Integer> myList = new ArrayList<> ();
  List<Integer> unModifiable;
  Set<Integer> mySet =new HashSet<> ();
  
  /* Add Elements to myList */
  for(int i=0; i < 10; i++){
   myList.add(i);
  }
  
  unModifiable = Collections.unmodifiableList(myList);
  
  /* Add Elements to mySet */
  for(int i=5; i < 15; i++){
   mySet.add(i);
  }
  
  System.out.println("Elements in unModifiable List are ");
  System.out.println(unModifiable +"\n");
  System.out.println("Elements in mySet are ");
  System.out.println(mySet +"\n");
  
  /* Add mySet Data to unModifiable List */
  unModifiable.addAll(mySet);
  
  System.out.println("Elements in myList after adding mySet are");
  System.out.println(myList); 
 }
}

Output
Elements in unModifiable List 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]

Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.addAll(Unknown Source)
        at ListAddAllUnsupported.main(ListAddAllUnsupported.java:26)


2. throws ClassCastException if the class of an element of the specified
Collection prevents it from being added to this list

3. throws NullPointerException if the specified collection contains one
or more null elements and this list does not permit null elements, or if the specified collection is null

4.throws IllegalArgumentException if some property of an element of the specified collection prevents it from being added to this list




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment