如何将一个长值转换为一个整数值在Java?
当前回答
使用toIntExact(long value)返回long参数的值,如果值溢出int值则抛出异常。它只适用于API等级24或以上。
int id = Math.toIntExact(longId);
其他回答
你需要对它进行类型转换。
long i = 100L;
int k = (int) i;
请记住,long类型的范围比int型更大,因此可能会丢失数据。
如果您谈论的是盒装类型,那么请阅读文档。
最好的简单方法是:
public static int safeLongToInt( long longNumber )
{
if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE )
{
throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
}
return (int) longNumber;
}
除了@Thilo接受的答案,数学。toIntExact在可选方法链中也很好用,尽管它只接受int作为参数
Long coolLong = null;
Integer coolInt = Optional.ofNullable(coolLong).map(Math::toIntExact).orElse(0); //yields 0
使用toIntExact(long value)返回long参数的值,如果值溢出int值则抛出异常。它只适用于API等级24或以上。
int id = Math.toIntExact(longId);
试试这个:
Int i = Long. valueof (L)// L:长值
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap