4

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

4

2 回答 2

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对象的引用并将其重新分配给由 创建的.add对象的引用)。

于 2012-08-29T10:18:04.077 回答
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);
于 2012-08-29T10:31:22.497 回答