微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

java中,BigInteger是不可变的,但我想理解为什么,因为很多时候它被用来做很多可以产生很多对象的计算.所以,让它变得不可变感觉有点直观.我想到的情况就是字符串操作,然后是StringBuilder的选项.应该有BigInteger的非永久性对应物吗?我认为在很多情况下这可能是有益的.

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

解决方法

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

Immutable classes
are easier to design,implement,and use than
mutable classes. They are less prone
to error and are more secure.

不可变对象很简单,因为对象只能存在于一个状态 – 它创建的状态.简单代码往往具有更少的错误.由于无法修改对象,因此在没有外部同步的情况下也是线程安全的.

Bloch使用BigInteger作为示例解决了不可变类的性能问题:

The only real disadvantage of immutable classes is that they require a
separate object for each distinct value. Creating these objects can be costly,
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.
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:明智地优化”).

原文地址:https://www.jb51.cc/java/130148.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐