2023-12-26 05:00:04

将Long转换为Integer

如何将一个长值转换为一个整数值在Java?


当前回答

在java中,有一种严格的方法将long类型转换为int类型

不仅lnog可以转换为int型,任何类型的类扩展数字可以转换为其他类型的数字一般,在这里我将告诉你如何转换一个长到int型,其他类型反之亦然。

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

其他回答

在java中,有一种严格的方法将long类型转换为int类型

不仅lnog可以转换为int型,任何类型的类扩展数字可以转换为其他类型的数字一般,在这里我将告诉你如何转换一个长到int型,其他类型反之亦然。

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

除了@Thilo接受的答案,数学。toIntExact在可选方法链中也很好用,尽管它只接受int作为参数

Long coolLong = null;
Integer coolInt = Optional.ofNullable(coolLong).map(Math::toIntExact).orElse(0); //yields 0

长期访客=1000;

int convVisitors =(int)访问者;

使用toIntExact(long value)返回long参数的值,如果值溢出int值则抛出异常。它只适用于API等级24或以上。

int id = Math.toIntExact(longId);

这里有三种方法:

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]