Why is BigInteger in java designed to be immutable?

In Java, BigInteger is immutable, but I want to understand why, because it is often used to do many calculations that can produce many objects So, making it immutable feels a little intuitive The situation I think of is string operation, and then the option of StringBuilder Should there be a non permanent counterpart to BigInteger? I think this may be beneficial in many cases

Editor: I know the benefits of invariance and how it can be beneficial in many cases I just want to know the benefits of BigInteger I use BigInteger to calculate the factorial of large numbers Therefore, I prefer the variable BigInteger Similarly, BigInteger will be used for calculations where the result is much larger than int For other cases, there is BigDecimal

Solution

Josh Bloch's effective Java explains the benefits of immutable classes in "item 15: minimizing variability":

Immutable objects are simple because an object can only exist in one state - the state it creates Simple code tends to have fewer errors Because the object cannot be modified, it is thread safe without external synchronization

Bloch uses BigInteger as an example to solve the performance problem of immutable classes:

So internally, BigInteger has made some optimizations for you If you really want a variable BigInteger, you can use BitSet, but please note that this may make your code more complex - and more error prone You should use the simplest solution (BigInteger) unless you are sure that using a variable version will bring you significant performance improvement (see also "item 55: wise optimization" in the same book)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>