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

Why BigInteger in java is designed to be immutable?

在 java 中,BigInteger 是不可变的,但我想了解为什么,因为很多时候它被用来做很多计算,这会产生很多对象。所以,不让它不可变感觉有点直观。我想到的情况类似于字符串操作,然后是 StringBuilder 的选项。是否应该有 BigInteger 的不可变对应物?我认为它可能在很多情况下都是有益的。

编辑:我知道不变性的好处以及它在许多情况下的好处。我只是想了解 w.r.t BigInteger 的好处。我已经使用 BigInteger 来计算大数的阶乘。所以,我更喜欢可变的 BigInteger。同样,BigInteger 将用于结果比 int 大得多的计算。对于其他情况,有 BigDecimal。

Josh Bloch 的

Effective Java 在 "Item 15: Minimize Mutability":

中解释了不可变 类 的好处

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),除非您确信使用可变版本会给您带来显着的性能提升(另请参阅同一本书中的 "Item 55: Optimize judiciously")。