2023-12-26 05:00:04

将Long转换为Integer

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


当前回答

在Java 8中,你可以使用Math.toIntExact。如果你想处理空值,使用:

Integer intVal = longVal == null ? null : Math.toIntExact(longVal);

这个方法的好处是,如果实参(long)溢出int型,它会抛出一个arithmeexception。

其他回答

你需要对它进行类型转换。

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

请记住,long类型的范围比int型更大,因此可能会丢失数据。

如果您谈论的是盒装类型,那么请阅读文档。

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

int id = Math.toIntExact(longId);

假设longVal不为空

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

比如y,你得到的对象可以是Integer也可以是Long。我知道这很丑陋,但它确实发生了……

长期访客=1000;

int convVisitors =(int)访问者;

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

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

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