Java中最常用的方法是验证转换long为int不会丢失任何信息?
这是我目前的实施:
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;
}
Run Code Online (Sandbox Code Playgroud)
Pie*_*ine 557
Java 8添加了一种新方法来实现这一目标.
import static java.lang.Math.toIntExact;
long foo = 10L;
int bar = toIntExact(foo);
Run Code Online (Sandbox Code Playgroud)
ArithmeticException如果发生溢出,将抛出.
Java 8中添加了其他几种溢出安全方法.它们以精确结尾.
例子:
Math.incrementExact(long)Math.subtractExact(long, long)Math.decrementExact(long)Math.negateExact(long),Math.subtractExact(int, int)Jon*_*eet 304
我想我会这样做:
public static int safeLongToInt(long l) {
if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
throw new IllegalArgumentException
(l + " cannot be cast to int without changing its value.");
}
return (int) l;
}
Run Code Online (Sandbox Code Playgroud)
我认为比重复铸造更清楚地表达了意图......但它有点主观.
注意潜在的兴趣 - 在C#中它只是:
return checked ((int) l);
Run Code Online (Sandbox Code Playgroud)
pra*_*pes 129
使用Google Guava的Ints类,您的方法可以更改为:
public static int safeLongToInt(long l) {
return Ints.checkedCast(l);
}
Run Code Online (Sandbox Code Playgroud)
来自链接的文档:
checkedCast时
public static int checkedCast(long value)
value如果可能,返回等于的int值.参数:
value-int类型范围内的任何值返回:
int等于 的值value抛出:
IllegalArgumentException- 如果value大于Integer.MAX_VALUE或小于Integer.MIN_VALUE
顺便说一下,你不需要safeLongToInt包装器,除非你想将它留在原地以便更改功能而不需要进行大量的重构.
Jai*_*aiz 29
使用BigDecimal:
long aLong = ...;
int anInt = new BigDecimal(aLong).intValueExact(); // throws ArithmeticException
// if outside bounds
Run Code Online (Sandbox Code Playgroud)
小智 17
这是一个解决方案,如果你不关心价值,以防它需要更大;)
public static int safeLongToInt(long l) {
return (int) Math.max(Math.min(Integer.MAX_VALUE, l), Integer.MIN_VALUE);
}
Run Code Online (Sandbox Code Playgroud)
And*_*eas 12
不要:这不是解决方案!
我的第一个方法是:
public int longToInt(long theLongOne) {
return Long.valueOf(theLongOne).intValue();
}
Run Code Online (Sandbox Code Playgroud)
但这只是将long转换为int,可能会创建新Long实例或从Long池中检索它们.
缺点
Long.valueOfLong如果数字不在Long池范围内,则创建一个新实例[-128,127].
该intValue实施确实不外乎:
return (int)value;
Run Code Online (Sandbox Code Playgroud)因此,这可以被认为不仅仅是铸造更糟糕long来int.
我声称看到是否更改值的显而易见的方法是转换并检查结果.但是,我会在比较时删除不必要的演员表.我也没有一个字母的变量名过于激烈(异常x和y,而不是在他们的意思,有时分别行和列()).
public static int intValue(long value) {
int valueInt = (int)value;
if (valueInt != value) {
throw new IllegalArgumentException(
"The long value "+value+" is not within range of the int type"
);
}
return valueInt;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果可能的话,我真的想避免这种转换.显然,有时它是不可能的,但在这些情况下IllegalArgumentException,就客户端代码而言,几乎肯定是错误的例外.
| 归档时间: |
|
| 查看次数: |
562884 次 |
| 最近记录: |