remove(Object): This method is available in java.util.TreeSet class of Java.
Syntax:
boolean java.util.TreeSet.remove(Object o)
This method takes one argument. This method removes the specified element from this set if it is present.
Parameters: One parameter is required for this method.
o: object to be removed from this set, if present.
Returns: true if this set contained the specified element.
Throws:
1. ClassCastException - if the specified object cannot be compared with the elements currently in this set.
2. NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
Approach 1: When no exception
Java
import java.util.TreeSet;public class TreeSetremove {public static void main(String[] args) {TreeSet<String> treeSet = new TreeSet<String>();treeSet.add("Hello");treeSet.add("Java");treeSet.add("Program");treeSet.add("C++");Object o = "Java";System.out.println(treeSet.remove(o));}}
Output:
true
Approach 2: NullPointerException
Java
import java.util.TreeSet;public class TreeSetremove {public static void main(String[] args) {TreeSet<String> treeSet = new TreeSet<String>();treeSet.add("Hello");treeSet.add("Java");treeSet.add("Program");treeSet.add("C++");Object o = null;System.out.println(treeSet.remove(o));}}
Output:
Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.TreeMap.getEntry(TreeMap.java:345) at java.base/java.util.TreeMap.remove(TreeMap.java:873) at java.base/java.util.TreeSet.remove(TreeSet.java:276)
No comments:
Post a Comment