Tuesday, 6 May 2014

Vector : addAll (Collection c)

public synchronized boolean addAll(Collection<? extends E> c)
Appends all of the elements in the specified Collection to the end of this Vector.
Return true if this Vector changed as a result of the call.

import java.util.*;

class VectorAddAll{
 public static void main(String args[]){
  Collection<Integer> myCollection;
  Vector<Integer> myVector;
  
  myCollection = new ArrayList<> ();
  myVector = new Vector<> ();
  
  /* Add Elements to myCollection */
  myCollection.add(10);
  myCollection.add(20);
  myCollection.add(30);
  
  /* Add Elements to myVector */
  myVector.add(40);
  myVector.add(50);
  myVector.add(60);
  
  System.out.println("Elements in myCollection are");
  System.out.println(myCollection);
  
  System.out.println("\nElements in myVector are");
  System.out.println(myVector);
  
  System.out.println("\nAdd myCollection to myVector");
  myVector.addAll(myCollection);
  
  System.out.println("\nElements in myVector are");
  System.out.println(myVector);
 }
}

Output
Elements in myCollection are
[10, 20, 30]

Elements in myVector are
[40, 50, 60]

Add myCollection to myVector

Elements in myVector are
[40, 50, 60, 10, 20, 30]

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

class VectorAddAllNullPointer{
 public static void main(String args[]){
  Collection<Integer> myCollection;
  Vector<Integer> myVector;
  
  myCollection = null;
  myVector = new Vector<> ();
  
  System.out.println("Add myCollection to myVector");
  myVector.addAll(myCollection);
 }
}

Output
Add myCollection to myVector
Exception in thread "main" java.lang.NullPointerException
        at java.util.Vector.addAll(Vector.java:880)
        at VectorAddAllNullPointer.main(VectorAddAllNullPointer.java:12)

 


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment