TreeSet headSet(K) in Java

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

Syntax:

SortedSet<K> java.util.TreeSet.headSet(K toElement)

This method takes one argument. This method returns a view of the portion of this set whose elements are strictly less than toElement.

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.

toElement: high endpoint (exclusive) of the returned set.

Returns:view of the portion of this set whose elements are strictly less than toElement.

Throws:

1. ClassCastException - if toElement is not compatible with this set's comparator.

2. NullPointerException - if toElement 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 toElement lies outside the bounds of the range

Approach 1: When no exception

Java

import java.util.TreeSet;

public class TreeSetheadSet {
    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 toElement = "C++";

        System.out.println(treeSet.headSet(toElement));

    }
}

Output:

[]


Approach 2: NullPointerException 

Java

import java.util.TreeSet;

public class TreeSetheadSet {
    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 toElement = null;

        System.out.println(treeSet.headSet(toElement));

    }
}

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:1646) at java.base/java.util.TreeMap$AscendingSubMap.<init>(TreeMap.java:2129) at java.base/java.util.TreeMap.headMap(TreeMap.java:1196) at java.base/java.util.TreeSet.headSet(TreeSet.java:336) at java.base/java.util.TreeSet.headSet(TreeSet.java:370)


No comments:

Post a Comment