我玩java.math.BigInteger。这是我的java类,
public class BigIntegerTest{
public static void main(String[] args) {
BigInteger fiveThousand = new BigInteger("5000");
BigInteger fiftyThousand = new BigInteger("50000");
BigInteger fiveHundredThousand = new BigInteger("500000");
BigInteger total = BigInteger.ZERO;
total.add(fiveThousand);
total.add(fiftyThousand);
total.add(fiveHundredThousand);
System.out.println(total);
}
}
我认为结果是555000
。但实际值是0
。为什么?
答案 0 :(得分:14)
BigInteger
个对象是不可变的。一旦创建,它们的值就无法改变。
当您致电.add
时,会创建并返回新 BigInteger对象,如果您想要访问其值,则必须存储该对象。
BigInteger total = BigInteger.ZERO;
total = total.add(fiveThousand);
total = total.add(fiftyThousand);
total = total.add(fiveHundredThousand);
System.out.println(total);
(可以说total = total.add(...)
,因为它只是移除对旧 total
对象的引用,并重新分配对 new 的引用一个由.add
创建的。
答案 1 :(得分:2)
试试这个
BigInteger fiveThousand = new BigInteger("5000");
BigInteger fiftyThousand = new BigInteger("50000");
BigInteger fiveHundredThousand = new BigInteger("500000");
BigInteger total = BigInteger.ZERO;
total = total.add(fiveThousand).add(fiftyThousand).add(fiveHundredThousand);
System.out.println(total);