BigInteger 类型的方法 add(long) 不可见

The method add(long) from the type BigInteger is not visible

如何将任何数字添加到 BigInteger?我在 eclipse 中收到此错误:-

The method add(long) from the type BigInteger is not visible

import java.math.BigInteger;

public class M  {
    public static void main(String[] args) {
        BigInteger a =  new BigInteger("20000423242342342354857948787922222222222388888888888888888");
        System.out.println("" + (a.add(2));
    }
}

您不能将普通整数添加到 BigInteger

但是您可以将一个 BigInteger 添加到另一个 BigInteger。所以你应该将原始整数转换为 BigInteger 如下:

System.out.println(b.add(BigInteger.valueOf(2)));

如果您查看 BigInteger 的源代码,您会看到一个用于添加长数值的重载方法。但是他们在方法描述中也提到了该方法是私有的。这就是为什么您无法从 class.

中调用它的原因
/**
     * Package private methods used by BigDecimal code to add a BigInteger
     * with a long. Assumes val is not equal to INFLATED.
     */
    BigInteger add(long val) {
        if (val == 0)
            return this;
        if (signum == 0)
            return valueOf(val);
        if (Long.signum(val) == signum)
            return new BigInteger(add(mag, Math.abs(val)), signum);
        int cmp = compareMagnitude(val);
        if (cmp == 0)
            return ZERO;
        int[] resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag));
        resultMag = trustedStripLeadingZeroInts(resultMag);
        return new BigInteger(resultMag, cmp == signum ? 1 : -1);
    }

顺便说一句,众所周知,编译器使用 valueOf() 方法将原始值转换为对象(拆箱)。并且 Java 自动将对象转换为原语 object.longValue() (自动装箱)。

    BigInteger iObject = BigInteger.valueOf(2L);
    long iPrimitive = iObject.longValue();

我相信您已经知道如何在这种情况下将它与 BigInteger add 方法一起用于 long 值。

    BigInteger b = new BigInteger("2000");
    b.add(BigInteger.valueOf(2L));

你也可以用这个版本(效率更高):

System.out.println(a.add(BigInteger.valueOf(2));

而且打印的时候不需要加"",因为值会自动转成字符串,然后打印。