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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...