我遇到了一个麻烦的问题,我无法真正向自己解释为什么会出现。
基本上,我想将时间添加到时间戳记(一个简单的长整数)。
我了解以下内容。如果我将时间添加到时间戳记中,我将来会结束。如果我将时间减去时间戳记,则表示过去已结束。
在我的示例中,反之亦然。如果我在时间戳上添加了一些内容,则减少了,如果减去了,则添加了一些内容。
public class MyClass {
public static void main(String args[]) {
static final int MONTH_IN_SECONDS = 2629743;
final long current = System.currentTimeMillis();
System.out.println("Current: " + current);
final long future = System.currentTimeMillis() + (MONTH_IN_SECONDS * 1000 * 3);
System.out.println("Addition: " + future);
final long past = System.currentTimeMillis() - (MONTH_IN_SECONDS * 1000 * 3);
System.out.println("Subtraction: " + past);
}
}
结果(比较前五个字符):
Current: 1582275101365
Addition: 1581574395774 // smaller than current even though it should be greater
Minus: 1582975806958 // great than current even though it should be smaller
为什么会这样? (MONTH_IN_SECONDS * 1000 * 3)
项是否因为它只是一个整数而溢出,因此计算不起作用(或以负值结尾),是否会溢出?
如果我将术语更改为(MONTH_IN_SECONDS * 1000L * 3)
,它似乎可以正常工作。是因为完整的术语被强制转换为long
吗?
问题在这里:
(MONTH_IN_SECONDS * 1000 * 3)
这是整数乘法,导致出现负数:
System.out.println((MONTH_IN_SECONDS * 1000 * 3));
输出-700705592
。您必须将MONTH_IN_SECONDS
声明为long
。
[(HAND_IN_SECONDS * 1000 * 3)项是否溢出,因为它是只能是整数,因此计算无法使用(或以负值)?
以秒为单位?谷歌说263万。 (尽管我看到您有2629743。)
2,630,000 * 1000 * 3 = 7,890,000,000
Integer.MAX_VALUE = 2^31 = 2,147,483,648
是的,这是一个整数溢出。