📌  相关文章
📜  Java中的 OptionalLong getAsLong() 方法及示例

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

Java中的 OptionalLong getAsLong() 方法及示例

OptionalLong帮助我们创建一个可能包含也可能不包含 long 值的对象。 getAsLong()方法返回值 如果 OptionalLong 对象中存在值,否则抛出NoSuchElementException

句法:

public long getAsLong()

参数:此方法不接受任何内容。

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

异常:如果不存在值,此方法将抛出NoSuchElementException

下面的程序说明了 getAsLong() 方法:

方案一:

// 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

方案二:

// 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: Java/util/OptionalLong.html#getAsLong()