Android studio 警告整数乘法隐式转换为 long。如何解决这个问题?

Android studio warns about integer multiplication implicitly cast to long. How to fix this?

 private static boolean isOverDate(long targetDate, int threshold) {
    return new Date().getTime() - targetDate >= threshold * 24 * 60 * 60 * 1000;
}

我正在使用上述功能,Android Studio 警告我:

threshold * 24 * 60 * 60 * 1000: integer multiplication implicitly cast to long 

如何解决这个问题?为什么会发出警告?

因为 max_int2 147 483 648

如果您的 threshold 大于 25 (25 * 24 * 60 * 60 * 1000 = 2.160.000.000),它将高于 int 可以容纳的值。所以你需要转换为 long 否则结果可能不正确。

参考:

If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.

解决方案:

long timeToCheck = threshold * 24 * 60 * 60 * 1000L;
return new Date().getTime() - targetDate >= timeToCheck;

或单行(这里不同的是最后一个数字后L,它会理解你将类型更改为long

return new Date().getTime() - targetDate >= threshold * 24 * 60 * 60 * 1000L;

或铸造

return new Date().getTime() - targetDate >= (long) threshold * 24 * 60 * 60 * 1000;

好的,所以拆开有点复杂。

>= 表达式的左手边(左侧)我们有:

new Date().getTime() - targetDate

该表达式的类型是 long 因为 targetDate 被声明为 long.

在 RHS 上我们有:

threshold * 24 * 60 * 60 * 1000

那是一个int因为所有的操作数都是int

但是该表达式可能溢出。 24 * 60 * 60 * 1000 的值“相当大”,当您将它乘以 threshold 时,结果值可能太大而无法表示为 int。如果它 确实 溢出,那么结果将被截断,并且 >= 测试将给出错误的结果。

所以...编译器建议您应该使用 long 算法进行 RHS 计算。简单的方法是将 threshold 声明为 long。但您也可以将其转换为 long,如:

((long) threshold) * 24 * 60 * 60 * 1000