如何防止Java代码中的整数溢出?
可能的重复:
如何检查在Java中相乘两个数字是否会导致溢出?
假设我有一个Java类方法,它使用和操作。*+
int foo(int a, int b) {
... // some calculations with + and *
}
如何确保没有溢出?foo
我想我可以使用或用“包装器”替换所有+和*,例如:BigDecimal
int sum(int a, int b) {
int c = a + b;
if (a > 0 && b > 0 && c < 0)
throw new MyOverfowException(a, b)
return c;
}
int prod(int a, int b) {
int c = a * b;
if (a > 0 && b > 0 && c < 0)
throw new MyOverfowException(a, b)
return c;
}
有没有更好的方法来确保Java方法中不会发生溢出?int