在 Java 中安全地将 long 转换为 int [英] Safely casting long to int in Java
本文介绍了在 Java 中安全地将 long 转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Java 中验证从 long
到 int
的转换不会丢失任何信息的最惯用的方法是什么?
What's the most idiomatic way in Java to verify that a cast from long
to int
does not lose any information?
这是我目前的实现:
public static int safeLongToInt(long l) {
int i = (int)l;
if ((long)i != l) {
throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
}
return i;
}
推荐答案
Java 8 添加了一种新方法来实现这一点.
A new method has been added with Java 8 to do just that.
import static java.lang.Math.toIntExact;
long foo = 10L;
int bar = toIntExact(foo);
在溢出时会抛出一个 ArithmeticException
.
Will throw an ArithmeticException
in case of overflow.
Java 8 中添加了其他几种溢出安全方法.它们以 exact 结尾.
Several other overflow safe methods have been added to Java 8. They end with exact.
示例:
Math.incrementExact(long)
Math.subtractExact(long, long)
Math.decrementExact(long)
Math.negateExact(long),
Math.subtractExact(int, int)
这篇关于在 Java 中安全地将 long 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文