Tuesday, 6 May 2014

Vector : containsAll : Search for a Collection of Elements

public synchronized boolean containsAll(Collection<?> c)
Returns true if this Vector contains all of the elements in the specified Collection.

import java.util.*;

class VectorContainsAll{
 public static void main(String args[]){
  Vector<Integer> myVector;
  Collection<Integer> myCollection1;
  Collection<Integer> myCollection2;
  
  myVector = new Vector<> ();
  myCollection1 = new ArrayList<> ();
  myCollection2 = new HashSet<> ();
  
  /* Add Elements to myVector */
  for(int i=1; i < 6; i++)
   myVector.addElement(i);
   
  /* Add Elements to myVector */
  for(int i=3; i < 6; i++)
   myCollection1.add(i);
   
  /* Add Elements to myVector */
  for(int i=3; i < 10; i++)
   myCollection2.add(i);
   
  System.out.println("Elements in myVector are");
  System.out.println(myVector);
  
  System.out.println("Elements in myCollection1 are");
  System.out.println(myCollection1);
  
  System.out.println("Elements in myCollection2 are");
  System.out.println(myCollection2);
  
  System.out.print("\nIs myVector contains myCollection1 ");
  System.out.println(myVector.containsAll(myCollection1));
  
  System.out.print("Is myVector contains myCollection2 ");
  System.out.println(myVector.containsAll(myCollection2));
 }
}

Output
Elements in myVector are
[1, 2, 3, 4, 5]
Elements in myCollection1 are
[3, 4, 5]
Elements in myCollection2 are
[3, 4, 5, 6, 7, 8, 9]

Is myVector contains myCollection1 true
Is myVector contains myCollection2 false

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

class VectorContainsAllNullPointer{
 public static void main(String args[]){
  Vector<Integer> myVector;
  Collection<Integer> myCollection1;
  
  myVector = new Vector<> ();
  myCollection1 = null;
  
  System.out.print("\nIs myVector contains myCollection1 ");
  System.out.println(myVector.containsAll(myCollection1));
 }
}

Output
Is myVector contains myCollection1 Exception in thread "main" java.lang.NullPointerException
        at java.util.AbstractCollection.containsAll(AbstractCollection.java:307)
        at java.util.Vector.containsAll(Vector.java:862)
        at VectorContainsAllNullPointer.main(VectorContainsAllNullPointer.java:12)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment