TreeSet tailSet(K) in Java

tailSet(K): This method is available in java.util.TreeSet class of Java.

Syntax:

SortedSet<K> java.util.TreeSet.tailSet(K fromElement)

This method takes one argument. This method returns a view of the portion of this set whose elements are greater than or equal to 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: One parameter is required for this method.

fromElement: low endpoint (inclusive) of the returned set.

Returns: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 TreeSettailSet {
    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";

        System.out.println(treeSet.tailSet(fromElement));

    }
}

Output:

[Java, Program]


Approach 2: NullPointerException

Java

import java.util.TreeSet;

public class TreeSettailSet {
    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;

        System.out.println(treeSet.tailSet(fromElement));

    }
}

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) at java.base/java.util.TreeSet.tailSet(TreeSet.java:381)


No comments:

Post a Comment