Java中的TreeSet floor()方法及示例

Java中的TreeSet floor()方法及示例

java.util.TreeSet ** 类的 **floor() 方法用于返回该集合中小于或等于给定元素的最大元素,如果没有这样的元素则返回null。

语法:

public E floor(E e)
Java

参数: 此方法将值 e 作为要匹配的参数。

返回值: 这个方法返回小于或等于e的元素中的最大元素,如果没有这样的元素,则返回 null

异常: 如果指定的元素为空并且此设置使用自然排序,或其比较器不允许空元素,则此方法会引发 NullPointerException

下面是说明 floor() 方法的示例。

示例1:

//演示使用floor()方法的Java程序
//对于整数值
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // create tree set object
            TreeSet<Integer> treeadd = new TreeSet<Integer>();
  
            // populate the TreeSet using add() method
            treeadd.add(10);
            treeadd.add(20);
            treeadd.add(30);
            treeadd.add(40);
  
            // Print the TreeSet
            System.out.println("TreeSet: " + treeadd);
  
            // getting the floor value for 25
            // using floor() method
            int value = treeadd.floor(25);
  
            // printing the floor value
            System.out.println("Floor value for 25: "
                               + value);
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
Java
TreeSet: [10, 20, 30, 40]
Floor value for 25: 20
Java

示例2: 对于NullPointerException

//演示使用floor()方法的Java程序
//对于NullPointerException
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
        try {
  
            // create tree set object
            TreeSet<Integer> treeadd = new TreeSet<Integer>();
  
            // populate the TreeSet using add() method
            treeadd.add(10);
            treeadd.add(20);
            treeadd.add(30);
            treeadd.add(40);
  
            // Print the TreeSet
            System.out.println("TreeSet: " + treeadd);
  
            // getting the floor value for null
            // using floor() method
            System.out.println("Trying to get"
                               + " the floor value"
                               + " for null");
  
            int value = treeadd.floor(null);
  
            // printing the floor value
            System.out.println("Floor value for 25: "
                               + value);
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
Java
TreeSet: [10, 20, 30, 40]
Trying to get the空元素的 floor 值
Exception thrown : java.lang.NullPointerException
Java

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册