- immutable類有個缺點,改變狀態或重新生成一個對象,比如String。BigInteger改變一個bit,就會重新構建一個對象。
BigInteger bigInteger = new BigInteger(new byte[]{127});
System.out.println(bigInteger);
System.out.println(bigInteger.flipBit(2));
BitSet是可mutable類,不會因爲改變了一個bit就重新生成一個對象
BitSet bitSet = new BitSet(8);
System.out.println(bitSet);
bitSet.set(0);
System.out.println(bitSet);
- 私有或包內私有構造器,再加一個靜態工廠,完成一個immutable class
static class Complex{
private final double re;
private final double im;
private Complex(double re, double im) {
this.re = re;
this.im = im;
}
public static Complex valueOf(double re, double im){
return new Complex(re, im);
}
}
- BigInteger或者BigDecimal本身是immutable對象,但是由於他們可以被繼承,他們的子類就可以是mutable對象。所以在需要用藥BigInteger
immutability的地方,需要驗證該對象是有BigInteger類實例化的,而不是BigInteger的子類。
public BigInteger safeInstance(BigInteger bigInteger){
return bigInteger.getClass() == BigInteger.class
? bigInteger : new BigInteger(bigInteger.toByteArray());
}