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


当前回答

long x;
int y;
y = (int) x

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

其他回答

如果使用Guava库,有方法Ints.checkedCast(long)和Ints.saturatedCast(long)用于将long转换为int。

如果您想进行安全的转换,并享受使用Java8和Lambda表达式 你可以这样使用它:

val -> Optional.ofNullable(val).map(Long::intValue).orElse(null)

在Java中,long是一个有符号的64位数字,这意味着您可以存储介于-9,223,372,036,854,775,808和9,223,372,036,854,775,807(包括)之间的数字。

另一方面,int是有符号的32位数字,这意味着您可以存储-2,147,483,648到2,147,483,647(包括)之间的数字。

因此,如果long值超出了int类型所允许的值,则无法进行值转换。

关于基本Java类型大小的详细信息如下:

http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

手动类型转换可以在这里完成:

long x1 = 1234567891;
int y1 = (int) x1;
System.out.println("in value is " + y1);
// 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
  }
}