java.math.MutableBigInteger的目的是什么?

java.math.MutableBigInteger只能从包内部获得。 它inheritance自java.lang.Object并且只有一个子类( SignedMutableBigInteger ),它只能从包内部获得。

 /** * A class used to represent multiprecision integers that makes efficient * use of allocated space by allowing a number to occupy only part of * an array so that the arrays do not have to be reallocated as often. * When performing an operation with many iterations the array used to * hold a number is only reallocated when necessary and does not have to * be the same size as the number it represents. A mutable number allows * calculations to occur on the same number without having to create * a new number for every step of the calculation as occurs with * BigIntegers. * * @see BigInteger * @version 1.12, 12/19/03 * @author Michael McCloskey * @since 1.3 */ 

来源 。

我猜MutableBigInteger在内部用于BigInteger繁重的计算,这些计算会因频繁的重新分配而变慢。 我不确定为什么它不作为java.math的一部分导出。 也许对可变价值类有些厌恶?

澄清“可变”:
标准BigInteger在其整个生命周期中都有一个值,给定两个BigInteger引用“a”和“b”,“a + b”将始终产生具有相同值的新BigInteger。 假设价值是4。

使用MutableBigInteger,“a + b”最初可以产生4,但由于其他代码更改了“a”引用的对象的值(也就是变异),因此在将来的某个时间点会产生8,16,32或任何其他数字。 “&”b“。 因此,Java中的大多数(可能是所有)值类型(Character,Short,Long,Integer,BigInteger,BigDecimal,Float,Double,甚至String)都是不可变的。

BigInteger的问题在于它是不可变的:换句话说,一旦你有一个BigInteger对象,你就无法改变对象本身的值,你只能用一个新对象替换它。

现在这通常是一件好事,因为它可以防止别名等等(你不希望你的“2 + 3”突然变成“2 + 5”,因为程序中其他地方的“3”用户把它改成了“5”)。 但是,BigInteger内部使用数组来保存此值的组件。 对于大量数字,这个数组可能非常大; 一个表示数百万的BigInteger可能需要一个数千个元素,比如说。

那么当我想在这个BigInteger中添加一个时会发生什么? 好吧,我们创建一个新的BigInteger,它将创建一个内部包含一千个元素的新数组,将旧BigInteger内部数组的所有元素复制到新BigInteger的内部数组,除了最后一个,然后放入最后一个元素的新版本加1。 (或者它可能需要更新最后两个。)如果您不需要旧值,它会释放旧的BigInteger,从而释放数组。

如果你只是摆脱旧的价值观,这显然是非常低效的。 因此,如果您有这样的操作,您可以改为使用MutableBigInteger,只需更改现有MutableBigInteger的内部数组中的最后一个元素即可增加它。 这要快得多! 但是,正如我在上面指出的那样,它确实会破坏旧值,这可能会有问题。 如果有人给你int“3”,你可以期望保持不变。 如果有人给你一个MutableBigInteger,不要指望它以后是相同的数字!

MutableBigInteger在java.math库中引用。 如果安装了JDK,请查看jdk目录中src.zip的内容。

你会看到BigInteger使用它:

 public BigInteger divide(BigInteger val) { MutableBigInteger q = new MutableBigInteger(), r = new MutableBigInteger(), a = new MutableBigInteger(this.mag), b = new MutableBigInteger(val.mag); a.divide(b, q, r); return new BigInteger(q, this.signum * val.signum); } 

MutableBigInteger是BigInteger使用的数学算法的封装。