TreeSet headSet(K, boolean) in Java

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

Syntax:

NavigableSet<K> java.util.TreeSet.headSet(K toElement, boolean inclusive)

This method takes two arguments. This method returns a view of the portion of this set whose elements are less than(or equal to, if inclusive is true) 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 of the returned set.

inclusive: true if the high-end point is to be included in the returned view.

Returns: a view of the portion of this set whose elements are less than(or equal to, if inclusive is true) 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 TreeSetheadSet2 {
    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++";
        boolean inclusive = true;

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

    }
}

Output:

[C++]


Approach 2: NullPointerException

Java

import java.util.TreeSet;

public class TreeSetheadSet2 {
    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;
        boolean inclusive = true;

        System.out.println(treeSet.headSet(toElement,
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: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)


No comments:

Post a Comment