lower(K): This method is available in java.util.TreeSet class of Java.
Syntax:
K java.util.TreeSet.lower(K e)
This method takes one argument. This method returns the greatest element in this set strictly less than 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 greatest element less than 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 TreeSetlower {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.lower("C++"));}}
Output:
null
Approach 2: NullPointerException
Java
import java.util.TreeSet;public class TreeSetlower {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.lower(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.getLowerEntry(TreeMap.java:492) at java.base/java.util.TreeMap.lowerKey(TreeMap.java:980) at java.base/java.util.TreeSet.lower(TreeSet.java:412)
No comments:
Post a Comment