Sunday 27 April 2014

TreeSet : removeAll : Remove collection from a Set

boolean removeAll(Collection<?> c)
Removes from this set all of its elements that are contained in the specified collection. return true if this set changed as a result of the call.

import java.util.*;
class TreeSetRemoveAll{
 public static void main(String args[]){
  Set<Integer> mySet = new TreeSet<> ();
  List<Integer> myList = new ArrayList<> ();
  
  /* Add Elements to mySet */
  mySet.add(10);
  mySet.add(20);
  mySet.add(30);
  
  /* Add Elements to myList */
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  System.out.println("\nElements in mySet are ");
  System.out.println(mySet);
  
  System.out.println("\nElements in myList are ");
  System.out.println(myList);
  
  mySet.removeAll(myList);
  
  System.out.println("\nElements after calling removeAll is ");
  System.out.println(mySet);
 }
}

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

Elements in myList are
[20, 30, 40]

Elements after calling removeAll is
[10]

1. throws ClassCastException if the class of an element of this set is incompatible with the specified collection

2. throws NullPointerException if this set contains a null element and the specified collection does not permit null elements or if the specified collection is null.

import java.util.*;
class TreeSetRemoveAllNullPointer{
 public static void main(String args[]){
  TreeSet<Integer> mySet = new TreeSet<> ();
  List<Integer> myList = null;
  
  /* Add Elements to mySet */
  mySet.add(10);
  mySet.add(20);
  mySet.add(30);
  
  System.out.println("\nElements in mySet are ");
  System.out.println(mySet);
  
  System.out.println("\nElements in myList are ");
  System.out.println(myList+"\n");
  
  mySet.removeAll(myList);
  
  System.out.println("\nElements after calling removeAll is ");
  System.out.println(mySet);
 }
}

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

Elements in myList are
null

Exception in thread "main" java.lang.NullPointerException
        at java.util.AbstractSet.removeAll(AbstractSet.java:171)
        at TreeSetRemoveAllNullPointer.main(TreeSetRemoveAllNullPointer.java:18)

As you observe the program, myList is null, trying to remove myList from mySet causes the NullPointerException.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment