当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java TreeSet ceiling()用法及代码示例


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

用法:

public E ceiling(E e)

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


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

异常:如果指定元素为null且此集合使用自然顺序,或者其比较器不允许使用null元素,则此方法将引发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


相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 TreeSet ceiling() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。