Convert Long into Integer

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

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

14条回答
  •  隐瞒了意图╮
    2020-12-07 08:20

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

    or if you don't need to worry about null:

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

    And in both situations, you might run into overflows (because a Long can store a wider range than an Integer).

    Java 8 has a helper method that checks for overflow (you get an exception in that case):

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

提交回复
热议问题