将Long转换为Integer

如何在Java中将Long值转换为Integer值?

 Integer i = theLong != null ? theLong.intValue() : null; 

或者如果你不需要担心null:

 // auto-unboxing does not go from Long to int directly, so Integer i = (int) (long) theLong; 

而且在这两种情况下,你可能会遇到溢出(因为Long可以存储比Integer更宽的范围)。

这里有三种方法来做到这一点:

 Long l = 123L; Integer correctButComplicated = Integer.valueOf(l.intValue()); Integer withBoxing = l.intValue(); Integer terrible = (int) (long) l; 

所有三个版本都生成几乎相同的字节码:

  0 ldc2_w <Long 123> [17] 3 invokestatic java.lang.Long.valueOf(long) : java.lang.Long [19] 6 astore_1 [l] // first 7 aload_1 [l] 8 invokevirtual java.lang.Long.intValue() : int [25] 11 invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29] 14 astore_2 [correctButComplicated] // second 15 aload_1 [l] 16 invokevirtual java.lang.Long.intValue() : int [25] 19 invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29] 22 astore_3 [withBoxing] // third 23 aload_1 [l] // here's the difference: 24 invokevirtual java.lang.Long.longValue() : long [34] 27 l2i 28 invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29] 31 astore 4 [terrible] 
 Integer intValue = myLong.intValue(); 

如果你在意检查溢出,并有番石榴方便,有Ints.checkedCast()

 int theInt = Ints.checkedCast(theLong); 

这个实现很简单,并且在溢出时抛出IllegalArgumentException :

 public static int checkedCast(long value) { int result = (int) value; checkArgument(result == value, "Out of range: %s", value); return result; } 

你需要input它。

 long i = 100L; int k = (int) i; 

请记住,长整数的范围比整数大,所以你可能会丢失数据。

如果您正在讨论盒装types,请阅读文档 。

最简单的方法是:

 public static int safeLongToInt( long longNumber ) { if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE ) { throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." ); } return (int) longNumber; } 

如果您正在使用Java 8,请按照以下步骤操作

  import static java.lang.Math.toIntExact; public class DateFormatSampleCode { public static void main(String[] args) { long longValue = 1223321L; int longTointValue = toIntExact(longValue); System.out.println(longTointValue); } } 

假设不为null longVal

 Integer intVal = ((Number)longVal).intValue(); 

它的作品例如你得到一个对象,可以是一个整数或一个长。 我知道这很丑陋,但事实恰恰相反

长途客人= 1000;

int convVisitors =(int)visitor;

在Java中,有一个严格的方法来将长整型转换为整型

不仅可以将lnog转换为int,任何types的extends数字都可以转换为其他Numbertypes,这里我将向您展示如何将long转换为int,反之亦然。

 Long l = 1234567L; int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);