在 Java 中,Long
和 Integer
类型之间的转换是常见的需求。由于 Long
的范围比 Integer
大,所以转换时需要注意潜在的数据丢失问题。以下是将 Long
转换为 Integer
和将 Integer
转换为 Long
的常见方法:
1. Long
转换为 Integer
使用强制类型转换
将 Long
转换为 Integer
可以通过强制类型转换完成。但请注意,这种方法没有范围检查,可能会导致数据丢失或溢出。
Long longValue = 123456789L;
Integer intValue = longValue.intValue();
使用 Math.toIntExact()
Math.toIntExact()
是 Java 8 引入的安全转换方法,它会在 Long
值超出 Integer
范围时抛出 ArithmeticException
异常。
Long longValue = 123456789L;
try {
Integer intValue = Math.toIntExact(longValue);
System.out.println