BigInteger total = BigInteger.ZERO;
total.add(BigInteger.valueOf(5000));
total.add(BigInteger.valueOf(50000));
total.add(BigInteger.valueOf(500000));
System.out.println(total); // 輸出 0,而非預期的 555000
BigInteger、String、BigDecimal 及所有包裝類(Integer、Long 等)均為 不可變類型。其方法不會修改原對象,而是返回新對象。
BigInteger total = BigInteger.ZERO;
total = total.add(BigInteger.valueOf(5000));
total = total.add(BigInteger.valueOf(50000));
total = total.add(BigInteger.valueOf(500000));
System.out.println(total); // 輸出 555000
Integer.valueOf(-128~127))可放心複用。Map 鍵或 Set 元素時,哈希碼穩定不變。| 錯誤寫法 | 正確寫法 | 說明 |
|---|---|---|
| s.replace("a", "b") 未賦值 | s = s.replace("a", "b") | String 方法返回新字符串 |
| list.add(1); 對 Integer 修改 | 不可修改,需 new Integer(2) | 包裝類無 setter |
| bd.setScale(2) 未接收 | bd = bd.setScale(2) | BigDecimal 同理 |
final,防止繼承破壞不變性。private final。new ArrayList<>(list))。