TreeSet floor(String) in Java

floor(String): This method is available in java.util.TreeSet class of Java.

Syntax:

String java.util.TreeSet.floor(String e)

This method takes one argument. This method returns the greatest element in this set less than or equal to 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 greatest element less than or equal to 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 TreeSetfloor {
    public static void main(String[] args) {

        TreeSet<String> treeSet = new TreeSet<String>();

        treeSet.add("Hello");
        treeSet.add("Java");
        treeSet.add("Program");
        treeSet.add("C++");

        System.out.println(treeSet.floor("Java"));

    }
}

Output:

Java


Approach 2: NullPointerException 

Java

import java.util.TreeSet;

public class TreeSetfloor {
    public static void main(String[] args) {

        TreeSet<String> treeSet = new TreeSet<String>();

        treeSet.add("Hello");
        treeSet.add("Java");
        treeSet.add("Program");
        treeSet.add("C++");

        System.out.println(treeSet.floor(null));

    }
}

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.getFloorEntry(TreeMap.java:427) at java.base/java.util.TreeMap.floorKey(TreeMap.java:1002) at java.base/java.util.TreeSet.floor(TreeSet.java:423)


No comments:

Post a Comment