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

Sai*_*Aye 4 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);
 }
}
Run Code Online (Sandbox Code Playgroud)

我认为结果是555000.但实际是0.为什么?

Aln*_*tak 14

BigInteger对象是不可变的.一旦创建,它们的值就无法更改.

当您调用新的 BigInteger对象时,会创建并返回.add该对象,并且如果要访问其值,则必须存储该对象.

BigInteger total = BigInteger.ZERO;
total = total.add(fiveThousand);
total = total.add(fiftyThousand);
total = total.add(fiveHundredThousand);
System.out.println(total);
Run Code Online (Sandbox Code Playgroud)

(可以这么说,total = total.add(...)因为它只是删除对 total对象的引用并将其重新分配给创建的对象的引用.add).

  • @PeterLawrey肯定,如果你知道你的价值只需要63位;-) (2认同)