ceiling(String): This method is available in java.util.TreeSet class of Java.
Syntax:
K java.util.TreeSet.ceiling(K e)
This method takes one argument. This method returns the least element in this set greater than or equal to the given element, or null if there is no such element.
Parameters: One parameter is required for this method.
e: the value to match.
Returns: the least element greater than or equal to e, or null if there is no such element.
Throws:
1. ClassCastException - if the specified element cannot be compared with the elements currently in the 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 TreeSetceiling {public static void main(String[] args) {TreeSet<String> treeSet = new TreeSet<String>();treeSet.add("Hello");treeSet.add("Java");treeSet.add("Program");treeSet.add("C++");System.out.println(treeSet.ceiling("Hello"));}}
Output:
Hello
Approach 2: NullPointerException
Java
import java.util.TreeSet;public class TreeSetceiling {public static void main(String[] args) {TreeSet<String> treeSet = new TreeSet<String>();treeSet.add("Hello");treeSet.add("Java");treeSet.add("Program");treeSet.add("C++");System.out.println(treeSet.ceiling(null));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "k1" is null at java.base/java.util.TreeMap.compare(TreeMap.java:1563) at java.base/java.util.TreeMap.getCeilingEntry(TreeMap.java:395) at java.base/java.util.TreeMap.ceilingKey(TreeMap.java:1024) at java.base/java.util.TreeSet.ceiling(TreeSet.java:434)
No comments:
Post a Comment