Convert Long into Integer

后端 未结 14 2146
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 07:48

How to convert a Long value into an Integer value in Java?

14条回答
  •  甜味超标
    2020-12-07 08:15

    If you care to check for overflows and have Guava handy, there is Ints.checkedCast():

    int theInt = Ints.checkedCast(theLong);
    

    The implementation is dead simple, and throws IllegalArgumentException on overflow:

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

提交回复
热议问题