📜  Java中的 TreeSet ceiling() 方法及示例

📅  最后修改于: 2022-05-13 01:54:32.805000             🧑  作者: Mango

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

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

句法:

public E ceiling(E e)

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

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

异常:如果指定元素为 null 并且此集合使用自然排序,或者其比较器不允许 null 元素,则此方法抛出NullPointerException

以下是说明天花板()方法的示例

示例 1:

// Java program to demonstrate
// ceiling() method
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // create tree set object
            TreeSet treeadd = new TreeSet();
  
            // populate the TreeSet
            treeadd.add(10);
            treeadd.add(20);
            treeadd.add(30);
            treeadd.add(40);
  
            // Print the TreeSet
            System.out.println("TreeSet: " + treeadd);
  
            // getting ceiling value for 25
            // using ceiling() method
            int value = treeadd.ceiling(25);
  
            // printing  the ceiling value
            System.out.println("Ceiling value for 25: "
                               + value);
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
TreeSet: [10, 20, 30, 40]
Ceiling value for 25: 30

示例 2:演示NullPointerException

// Java program to demonstrate
// ceiling() method for NullPointerException
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // create tree set object
            TreeSet treeadd = new TreeSet();
  
            // populate the TreeSet
            treeadd.add(10);
            treeadd.add(20);
            treeadd.add(30);
            treeadd.add(40);
  
            // Print the TreeSet
            System.out.println("TreeSet: " + treeadd);
  
            // getting ceiling value for null
            // using ceiling() method
            System.out.println("Trying to compare"
                               + " with null value ");
  
            int value = treeadd.ceiling(null);
  
            // printing  the ceiling value
            System.out.println("Ceiling value for null: " + value);
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception: " + e);
        }
    }
}
输出:
TreeSet: [10, 20, 30, 40]
Trying to compare with null value 
Exception: java.lang.NullPointerException