Friday, 21 March 2014

Clears elements in a set

void clear()
    Removes all of the elements from this set.

import java.util.*;
class SetClear{
 public static void main(String args[]){
  Set<Integer> mySet = new HashSet<Integer> ();
  
  /*Adding Elements to mySet */
  mySet.add(10);
  mySet.add(20);
  mySet.add(30);
  
  /* print mySet */
  System.out.println("Elements in mySet are " + mySet);
  
  /* Clearing the elements of mySet */
  mySet.clear();
  
  System.out.println("\nElements after clearing mySet is");
  System.out.println(mySet);

 }
}
Output

Elements in mySet are [20, 10, 30]

Elements after clearing mySet is
[]

 
1. Clear throws UnsupportedOperationException if the clear method
is not supported by this set.

Example: You can't clear the elements from unmodifiable Set. Trying to do so causes the UnsupportedOperationException.
 
import java.util.*;
class SetClearUnSupport{
 public static void main(String args[]){
  Set<Integer> mySet = new HashSet<Integer> ();
  Set<Integer> unmodifySet;
  
  /*Adding Elements to mySet */
  mySet.add(10);
  mySet.add(20);
  mySet.add(30);
    
  unmodifySet= Collections.unmodifiableSet(mySet);
  
  /* print mySet */
  System.out.println("Elements in mySet are " + mySet);
  System.out.println("Elements in unmodifySet are " + unmodifySet);
  
  /* Clearing the elements of mySet */
  unmodifySet.clear();

 }
}

Output

Elements in mySet are [20, 10, 30]
Elements in unmodifySet are [20, 10, 30]
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.clear(Unknown Source)
        at SetClearUnSupport.main(SetClearUnSupport.java:19)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment