tailSet(K, boolean): This method is available in java.util.TreeSet class of Java.
Syntax:
NavigableSet<K> java.util.TreeSet.tailSet(K fromElement, boolean inclusive)
This method takes two arguments. This method returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.
Note: The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa.
Parameters: Two parameters are required for this method.
fromElement: low endpoint of the returned set.
inclusive: true if the low endpoint is to be included in the returned view.
Returns: a view of the portion of this set whose elements are greater than or equal to fromElement
Throws:
1. ClassCastException - if fromElement is not compatible with this set's comparator.
2. NullPointerException - if fromElement is null and this set uses natural ordering, or its comparator does not permit null elements.
3. IllegalArgumentException - if this set itself has a restricted range, and fromElement lies outside the bounds of the range.
Approach 1: When no exception
Java
import java.util.TreeSet;public class TreeSettailSet2 {public static void main(String[] args) {TreeSet<String> treeSet = new TreeSet<String>();treeSet.add("Hello");treeSet.add("Java");treeSet.add("Program");treeSet.add("C++");String fromElement = "Java";boolean inclusive = true;System.out.println(treeSet.tailSet(fromElement,inclusive));}}
Output:
[Java, Program]
Approach 2: NullPointerException
Java
import java.util.TreeSet;public class TreeSettailSet2 {public static void main(String[] args) {TreeSet<String> treeSet = new TreeSet<String>();treeSet.add("Hello");treeSet.add("Java");treeSet.add("Program");treeSet.add("C++");String fromElement = null;boolean inclusive = true;System.out.println(treeSet.tailSet(fromElement,inclusive));}}
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$NavigableSubMap.<init>(TreeMap.java:1644) at java.base/java.util.TreeMap$AscendingSubMap.<init>(TreeMap.java:2129) at java.base/java.util.TreeMap.tailMap(TreeMap.java:1210) at java.base/java.util.TreeSet.tailSet(TreeSet.java:348)
No comments:
Post a Comment