2023-12-26 05:00:04

将Long转换为Integer

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


当前回答

如果你想检查溢出并且手边有Guava,有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;
}

其他回答

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类型存储更大的范围)。

Java 8有一个helper方法来检查溢出(在这种情况下你会得到一个异常):

Integer i = theLong == null ? null : Math.toIntExact(theLong);

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

int id = Math.toIntExact(longId);

对于非空值:

Integer intValue = myLong.intValue();

长期访客=1000;

int convVisitors =(int)访问者;

如果你想检查溢出并且手边有Guava,有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;
}