这是Duration
类中的方法toNanos
public long toNanos() {
long tempSeconds = seconds;
long tempNanos = nanos;
// TODO: Here makes me confused
if (tempSeconds < 0) {
// change the seconds and nano value to
// handle Long.MIN_VALUE case
tempSeconds = tempSeconds + 1;
tempNanos = tempNanos - NANOS_PER_SECOND;
}
long totalNanos = Math.multiplyExact(tempSeconds, NANOS_PER_SECOND);
totalNanos = Math.addExact(totalNanos, tempNanos);
return totalNanos;
}
我不明白为什么在秒为负值的情况下还需要做额外的工作.
正数的最大值是2^63-1
,负数的最小值是2^63
,看起来是从-2^63s,-1ns
转到-2^63+1s,1000_000_000-1ns
,但最终还是要参与计算.在我看来,这是没有意义的,因为Math.multiplyExact
和Math.addExact
会在数字溢出时抛出异常,无论判断是否存在,它都不会改变