编辑:我知道不变性的好处以及它在许多情况下是如何有益的.我只是想了解一下BigInteger的好处.我用BigInteger来计算大数的阶乘.所以,我更喜欢可变的BigInteger.类似地,BigInteger将用于结果远大于int的计算.对于其他情况,有BigDecimal.
解决方法
Immutable classes@H_404_10@ are easier to design,implement,and use than@H_404_10@ mutable classes. They are less prone@H_404_10@ to error and are more secure.
不可变对象很简单,因为对象只能存在于一个状态 – 它创建的状态.简单代码往往具有更少的错误.由于无法修改对象,因此在没有外部同步的情况下也是线程安全的.
Bloch使用BigInteger作为示例解决了不可变类的性能问题:
The only real disadvantage of immutable classes is that they require a@H_404_10@ separate object for each distinct value. Creating these objects can be costly,@H_404_10@ especially if they are large. […]
Internally,the immutable class can be arbitrarily clever. For example,BigInteger has a package-private mutable “companion class” that it uses to speed up multistep operations such as modular exponentiation.@H_404_10@ It is much harder to use the mutable companion class than to use BigInteger for all of the reasons outlined earlier,but luckily you don’t have to: the implementors of BigInteger did the hard work for you.
所以在内部,BigInteger已经为您做了一些优化.如果你真的想要一个可变的BigInteger,你可以使用BitSet
,但请注意,这可能会使你的代码更复杂 – 而且更容易出错.您应该使用最简单的解决方案(BigInteger),除非您确信使用可变版本会给您带来明显的性能提升(另请参阅同一本书中的“项目55:明智地优化”).