如何在Java中将long转换为int ?


当前回答

从Java 8开始 你可以使用:数学。toIntExact(长值)

参见JavaDoc: Math.toIntExact

返回长参数的值;如果值溢出int,则抛出异常。

数学的源代码。在JDK 8中的toIntExact:

public static int toIntExact(long value) {
    if ((int)value != value) {
        throw new ArithmeticException("integer overflow");
    }
    return (int)value;
}

其他回答

您可以使用Long包装器而不是Long原语和调用

Long.intValue()

Java7 intValue()文档

它对长值进行四舍五入/截断以适应int类型。

Long x = 100L;
int y = x.intValue();

我也遇到过这个问题。 为了解决这个问题,我首先将我的long转换为String,然后转换为int。

int i = Integer.parseInt(String.valueOf(long));
// Java Program to convert long to int
  
class Main {
  public static void main(String[] args) {
  
    // create long variable
    long value1 = 523386L;
    long value2 = -4456368L;
  
    // change long to int
    int num1 = Math.toIntExact(value1);
    int num2 = Math.toIntExact(value2);
      
    // print the type
    System.out.println("Converted type: "+ ((Object)num1).getClass().getName());
    System.out.println("Converted type: "+ ((Object)num2).getClass().getName());
  
    // print the int value
    System.out.println(num1);  // 52336
    System.out.println(num2);  // -445636
  }
}
long x;
int y;
y = (int) x

只要数字小于2147483647,就可以将long类型转换为int类型而不会出错。