本文翻译自:Safely casting long to int in Java
What's the most idiomatic way in Java to verify that a cast from long
to int
does not lose any information? 在Java中验证从long
到int
强制转换不丢失任何信息的最惯用的方法是什么?
This is my current implementation: 这是我目前的实施:
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;
}
#1楼
参考:https://stackoom.com/question/6fqZ/在Java中安全地将long转换为int
#2楼
here