java.math.BigInteger的用法是错误的吗?

时间:2012-08-29 10:16:57

标签: java biginteger

我玩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。为什么?

2 个答案:

答案 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);