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


Java OptionalLong getAsLong()用法及代碼示例


OptionalLong幫助我們創建一個可能包含或可能不包含long值的對象。 getAsLong()方法返回值如果OptionalLong對象中存在一個值,否則拋出NoSuchElementException。

用法:

public long getAsLong()

參數:此方法不接受任何內容。


返回值:此方法返回此OptionalLong描述的值。

異常:如果不存在任何值,則此方法將引發NoSuchElementException

以下示例程序旨在說明getAsLong()方法:

示例1:

// Java program to demonstrate 
// OptionalLong.getAsLong() method 
  
import java.util.OptionalLong; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
  
        // Create an OptionalLong instance 
        OptionalLong opLong = OptionalLong.of(445325); 
  
        System.out.println("OptionalLong: "
                           + opLong.toString()); 
  
        // Get value in this instance 
        // using getAsLong() 
        System.out.println("Value in OptionalLong = "
                           + opLong.getAsLong()); 
    } 
}
輸出:
OptionalLong: OptionalLong[445325]
Value in OptionalLong = 445325

示例2:

// Java program to demonstrate 
// OptionalLong.getAsLong() method 
  
import java.util.OptionalLong; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
  
        try { 
  
            // Create an OptionalLong instance 
            OptionalLong opLong = OptionalLong.empty(); 
  
            System.out.println("OptionalLong: "
                               + opLong.toString()); 
  
            // Get value in this instance 
            // using getAsLong() 
            System.out.println("Value in OptionalLong = "
                               + opLong.getAsLong()); 
        } 
        catch (Exception e) { 
  
            System.out.println("Exception: " + e); 
        } 
    } 
}
輸出:
OptionalLong: OptionalLong.empty
Exception: java.util.NoSuchElementException: No value present

參考文獻: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalLong.html#getAsLong()



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 OptionalLong getAsLong() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。