将Long转换为Integer [英] Convert Long into Integer

查看:1513
本文介绍了将Long转换为Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换 Long 值转换为 Integer 值Java?

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

推荐答案

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

或者如果您不需要担心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;

在两种情况下,您都可能会遇到溢出(因为Long可以存储的范围比Integer更大).

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

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

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);

这篇关于将Long转换为Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆