Android Studio报整数乘法隐式转换为long警告该如何解决?
警告触发原因
首先代码里参与乘法运算的threshold是int类型,24、60、1000等常量默认也属于int类型,整个乘法运算默认会按照int规则执行:
- Java中
int类型的取值范围是-2^31~2^31-1(即-2147483648 ~ 2147483647),当threshold取值稍大时,乘积很容易超出int的最大值,发生整数溢出,得到错误的结果 - 运算完成后,因为左侧
new Date().getTime() - targetDate的结果是long类型,所以溢出后的int结果会被隐式转换为long,但溢出已经发生,转换后结果依然不正确,因此Android Studio弹出该警告提示风险
修复方案
核心思路是让乘法运算全程按照long类型执行,避免整数溢出,可选方案如下:
- 方案1:将任意一个乘数显式声明为
long类型,运算时所有操作数会自动向上提升为long,不会发生溢出。推荐在乘数最前面加1L,改动最小也最直观:
private static boolean isOverDate(long targetDate, int threshold) { return new Date().getTime() - targetDate >= 1L * threshold * 24 * 60 * 60 * 1000; }
也可以直接将末尾的1000改成1000L,效果一致。
- 方案2:使用JDK内置的时间工具类完成换算,代码可读性更高,也不会出现手动计算系数的错误:
import java.util.concurrent.TimeUnit; private static boolean isOverDate(long targetDate, int threshold) { return new Date().getTime() - targetDate >= TimeUnit.DAYS.toMillis(threshold); }
- 方案3:直接将
threshold参数的类型修改为long,后续乘法运算会自动按long执行,该方案适合方法调用范围较小、修改成本低的场景。
内容的提问来源于stack exchange,提问作者Chaitanya Karmarkar
相关产品推荐
相关产品推荐

