java - 在java中自动装箱/将Long强制转换为int的更简单方法

标签 java casting

我有以下 Java 代码:

void foo(int a) { ... }

void bar() {
    Long x = 42;
    foo(x);  // Compile error: "Method foo(int)   
             // is not applicable for the argument (long)"
    foo((long) x); // Same as before
    foo((int) x); // Compile error: "Cannot cast Long to int"
    foo((int) (long) x);  // OK, but strange and confusing
}

有更好的方法吗?

最佳答案

如果您有一个 Long 对象,则可以调用 intValue() method获得一个int

关于java - 在java中自动装箱/将Long强制转换为int的更简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19122546/

相关文章:

java 试图分配较弱的访问权限错误

c# - 将 char 转换为 unsigned short : what happens behind the scenes?

java - 装饰一个继承 protected 可观察对象的类

Java并发数据结构

java - 如何摆脱 Android Studio 上的可疑调用警告?

casting - D中的整数到字符串转换

c++ - 将非模板基类向下转换为模板化派生类 : is it possible?

c# - 捕获的变量... 'Captured' 实际上代表什么?

java - play2 framework 我的模板没见过。 : package views. html不存在

java - 从文本文件中读取大量数据的最快方法