Item17 Minimize Mutability

本文探讨了immutable类如String和BigInteger的特性,特别是在改变状态时重新生成对象的问题。对比了mutable类BitSet在修改状态时的效率优势。并介绍了如何通过私有构造器和静态工厂方法创建immutable类。同时,提醒在使用BigInteger时需注意其可被继承导致的潜在mutable风险。
  • 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());
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值