错误案例
【现象描述】用BigInteger相加,永远返回0
【错误代码】
BigInteger total = BigInteger.ZERO; total.add(new BigInteger("1")); total.add(new BigInteger("10")); System.out.println(total);
上面程序的结果为11吗?答案是0
错误分析
BigInteger实例是不可变的, String、BigDecimal以及包装类型:Integer、Long、Short、Byte、Character、Boolean、Float和Double也是如此。对这些类型的操作将返回新的实例。
正确用法
BigInteger total = BigInteger.ZERO; total=total.add(new BigInteger("1")); total=total.add(new BigInteger("10")); System.out.println(total);
上面程序的结果为什么?答案是11