- 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());
}
本文探讨了immutable类如String和BigInteger的特性,特别是在改变状态时重新生成对象的问题。对比了mutable类BitSet在修改状态时的效率优势。并介绍了如何通过私有构造器和静态工厂方法创建immutable类。同时,提醒在使用BigInteger时需注意其可被继承导致的潜在mutable风险。
77

被折叠的 条评论
为什么被折叠?



