TreeSet higher(K) in Java

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

Syntax:

K java.util.TreeSet.higher(K e)

This method takes one argument. This method returns the least element in this set strictly greater 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 least element greater 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 TreeSethigher {
    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 e = "C++";

        System.out.println(treeSet.higher(e));

    }
}

Output:

Hello


Approach 2: NullPointerException 

Java

import java.util.TreeSet;

public class TreeSethigher {
    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 e = null;

        System.out.println(treeSet.higher(e));

    }
}

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.getHigherEntry(TreeMap.java:461) at java.base/java.util.TreeMap.higherKey(TreeMap.java:1046) at java.base/java.util.TreeSet.higher(TreeSet.java:445)


No comments:

Post a Comment