2012-08-29 27 views
4

我玩弄java.math.BigInteger。這是我的java類,java.math.BigInteger的用法是否錯誤?

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。爲什麼?

回答

14

BigInteger對象是不可變的。他們的價值一旦創造就無法改變。

當你調用一個.addBigInteger的對象被創建並返回,如果您要訪問其值必須存儲。

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創建)。

+1

+1使用'long'是* *很多簡單的,當然。 –

+2

@PeterLawrey當然,如果你知道你的值只需要63位;-) – Alnitak

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); 
+0

+1用於演示'.add()'的鏈接。 – Alnitak

相關問題