- 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());
}