最佳答案
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 有一个检查溢出的辅助方法(在这种情况下会出现异常):
Integer i = theLong == null ? null : Math.toIntExact(theLong);
关于java - 将 Long 转换为 Integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5804043/