Integer 强转成 long
1、基本实现
- 可以直接用
(long)变量名对 Integer 包装类对象进行强制转换
Integernum=100;longres=(long)num;- 上述代码的执行过程:Integer 对象 -> 自动拆箱 -> int 基本值 -> 强转 -> long 基本值,等价于如下代码
Integernum=100;longres=(long)num.intValue();2、解读
Java 为 8 种基本类型 + 包装类设计了自动拆箱机制,当包装类对象(Integer)出现在需要基本类型(int)的场景时(例如,强转、算术运算),JVM 会自动调用包装类的 intValue 方法,把包装类对象转换为对应的基本类型值
int 和 long 都是 Java 的基本数值类型,且 long 的取值范围完全包含 int 的取值范围
小范围基本类型转换为大范围基本类型的强转是安全的,不会有精度丢失、不会有数据溢出,转换后数值和原值完全一致
3、其他实现
Integernum=6789;longres=num.longValue();Integernum=6789;longres=Long.valueOf(num);4、注意事项
- Integer 是包装类,可以赋值为 null,如果对 null 的 Integer 对象执行强转,会直接抛出 NullPointerException 空指针异常
Integernum=null;longres=(long)num;# 输出结果 Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "num" is nullIntegernum=null;longres=Long.valueOf(num);# 输出结果 Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "num" is null