當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。