世界上并没有完美的程序,但我们并不因此而沮丧,因为写程序本来就是一个不断追求完美的过程。 ——摘自周志明

记录BigInteger犯过的一个错误

public class StrTest {
    public static void main(String[] args) {
        BigInteger a = new BigInteger("1");
        BigInteger b = new BigInteger("2");
        BigInteger c = new BigInteger("3");
        BigInteger d = new BigInteger("0");

        d.add(a);
        d.add(b);
        d.add(c);
//        BigInteger result = d.add(a).add(b).add(c);
        System.out.println(d.toString());
    }
}

打印结果为:0

经过查看add()源码,看到如下代码:

public BigInteger add(BigInteger val) {
        if (val.signum == 0)
            return this;
        if (signum == 0)
            return val;
     //注意:这里返回了新对象
if (val.signum == signum) return new BigInteger(add(mag, val.mag), signum); int cmp = compareMagnitude(val); if (cmp == 0) return ZERO; int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) : subtract(val.mag, mag)); resultMag = trustedStripLeadingZeroInts(resultMag); return new BigInteger(resultMag, cmp == signum ? 1 : -1); }

 

posted @ 2019-04-18 23:04  白杯与咖啡  阅读(271)  评论(0编辑  收藏  举报