为什么java中的BigInteger被设计为不可变的?

前端之家收集整理的这篇文章主要介绍了为什么java中的BigInteger被设计为不可变的?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
java中,BigInteger是不可变的,但我想理解为什么,因为很多时候它被用来做很多可以产生很多对象的计算.所以,让它变得不可变感觉有点直观.我想到的情况就是字符串操作,然后是StringBuilder的选项.应该有BigInteger的非永久性对应物吗?我认为在很多情况下这可能是有益的.

编辑:我知道不变性的好处以及它在许多情况下是如何有益的.我只是想了解一下BigInteger的好处.我用BigInteger来计算大数的阶乘.所以,我更喜欢可变的BigInteger.类似地,BigInteger将用于结果远大于int的计算.对于其他情况,有BigDecimal.

解决方法

Josh Bloch的 Effective Java在“第15项:最小化可变性”中解释了不可变类的好处:

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:明智地优化”).

猜你在找的Java相关文章