Home »
Java programming language
Java TreeSet remove() Method with Example
TreeSet Class remove() method: Here, we are going to learn about the remove() method of TreeSet Class with its syntax and example.
Submitted by Preeti Jain, on February 20, 2020
TreeSet Class remove() method
- remove() method is available in java.util package.
- remove() method is used to remove the given object (ob) when exists in this TreeSet.
- remove() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
-
remove() method may throw an exception at the time of removing an object.
- ClassCastException: This exception may throw when the given parameter is incompatible.
- NullPointerException: This exception may throw when the given parameter is null exists.
Syntax:
public boolean remove(Object ob);
Parameter(s):
- Object ob – represents the object (ob) to be remove from this TreeSet.
Return value:
The return type of the method is boolean, it returns true when the given object (ob) is to be removed successfully otherwise it returns false.
Example:
// Java program to demonstrate the example
// of boolean remove(Object ob) method of TreeSet
import java.util.*;
public class RemoveOfTreeSet {
public static void main(String[] args) {
// Instantiates a TreeSet object
TreeSet < String > tree_set = new TreeSet < String > ();
// By using add() method is to add
// the given object of this TreeSet
tree_set.add("C");
tree_set.add("C++");
tree_set.add("JAVA");
tree_set.add("PHP");
tree_set.add("SFDC");
// Display TreeSet
System.out.println("TreeSet: " + tree_set);
// By using remove() method is to
// remove the given object exists in
// this TreeSet
boolean status = tree_set.remove("PHP");
// Display status
System.out.println("tree_set.remove(PHP): " + status);
// Display Modified TreeSet
System.out.println("Modified TreeSet: " + tree_set);
}
}
Output
TreeSet: [C, C++, JAVA, PHP, SFDC]
tree_set.remove(PHP): true
Modified TreeSet: [C, C++, JAVA, SFDC]