Saturday 26 April 2014

TreeSet : remove : Remove Element from the Set

boolean remove(Object o)
Removes the specified element from this set if it is present. Returns true if the Element removed else false.

import java.util.*;
class TreeSetRemove{
 public static void main(String args[]){
  TreeSet<Integer> mySet =new TreeSet<> ();
  
  /* Add elements to the set */
  mySet.add(1);
  mySet.add(-10);
  mySet.add(100);
  mySet.add(12);
  mySet.add(14);
  
  /* Display the set */
  System.out.println("Elements in mySet are");
  System.out.println(mySet);
  
  /* Removing -10 from the set */
  mySet.remove(-10);
  
  System.out.println("\nElements in mySet After removing -10 are");
  System.out.println(mySet);  
 }
}

Output
Elements in mySet are
[-10, 1, 12, 14, 100]

Elements in mySet After removing -10 are
[1, 12, 14, 100]

1. Throws ClassCastException if the type of the specified element is incompatible with this set
class Employee{
 int number;
 
 Employee(int number){
  this.number = number;
 }
}

import java.util.*;
class SetClassCastRemove{
 public static void main(String args[]){
  TreeSet<Employee> mySet = new TreeSet<> ();
  
  Employee e1 = new Employee(1);
  boolean flag = mySet.remove(e1);
  
  System.out.println("Is Employee Removed " + flag);
 }
}

Output
Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast
 to java.lang.Comparable
        at java.util.TreeMap.getEntry(TreeMap.java:343)
        at java.util.TreeMap.remove(TreeMap.java:595)
        at java.util.TreeSet.remove(TreeSet.java:276)
        at SetClassCastRemove.main(SetClassCastRemove.java:7)

To make the program compiles fine, Make the Employee class to implement Comparable interface.

class Employee implements Comparable{
 int number;
 
 public int compareTo(Object emp){
  if(emp==null)
   return 0;
  
  Employee e = (Employee) emp;
  
  if(this.number == e.number)
   return 0;
   
  return (this.number - e.number);
 }
 
 Employee(int number){
  this.number = number;
 } 
 
 public String toString(){
  return "Employee " + number;
 }
 
}

Output
Is Employee Removed false

2.Throws NullPointerException if the specified element is null and this set does not permit null elements.

import java.util.*;
class TreeSetRemoveNull{
 public static void main(String args[]){
  TreeSet<Integer> mySet = new TreeSet<> ();
  mySet.remove(null);
 }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.getEntry(TreeMap.java:342)
        at java.util.TreeMap.remove(TreeMap.java:595)
        at java.util.TreeSet.remove(TreeSet.java:276)
        at TreeSetRemoveNull.main(TreeSetRemoveNull.java:5)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment