Java TreeSet ceiling()方法及实例

Java TreeSet ceiling()方法及实例

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

语法

public E ceiling(E e)

参数: 该方法以值e为参数,要进行匹配。

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

异常: 如果指定的元素是空的,而这个集合使用自然排序,或者它的比较器不允许空元素,这个方法会抛出 NullPointerException

下面是一些例子来说明 ceiling() 方法

例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<Integer> treeadd = new TreeSet<Integer>();
  
            // 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<Integer> treeadd = new TreeSet<Integer>();
  
            // 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程