正在初始化 java.math.BigInteger

Initializing java.math.BigInteger

抱歉,这可能看起来像一个愚蠢的是或否问题,但我对此很陌生,所以我需要一个答案。

BigInteger i = BigInteger.valueOf(0);

BigInteger i = new BigInteger("0");

它们一样吗?

它们都以对值为 0 的 BigInteger 的引用结束,但它们在效果上并不相同。特别是,由于valueOf是一个静态方法,它可以利用缓存,并且return如果你调用它两次相同的引用:

BigInteger a = BigInteger.valueOf(0);
BigInteger b = BigInteger.valueOf(0);
System.out.println(a == b); // true on my machine

这似乎没有保证,但鉴于documentation:[=17]肯定有些符合预期 =]

Returns a BigInteger whose value is equal to that of the specified long. This "static factory method" is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers.

当你调用构造函数时,你真的每次都会得到一个新的实例。

就是说,对于这个特定的例子,我只使用 BigInteger.ZERO...

让我们做一个快速实验:

@Test
public void testBigIntegers() {
    assertThat(BigInteger.valueOf(0), is(new BigInteger("0")));
}

所以,准确地说:这里有两个 equal BigInteger 对象。 由于 BigInteger 构造函数只允许输入 "whole" 整数;对于 valueOf() 能够为您提供的所有值都是如此。

但是因为这两个对象是以不同的方式创建的,所以这里确实有 两个 不同的对象。而两次调用 valueOf(0) 很可能会为两次调用提供 相同的 对象(参考)。

是的,在这种情况下,它们是相同的(如果 "same" 你的意思是 "instances that are equal"),你也可以说 BigInteger.ZERO.

但是对于非常大的数字,您只能使用 String 构造函数:

new BigInteger("12345678901234567890123456789012345")  // too long for long
  BigInteger i = BigInteger.valueOf(0);
                BigInteger i1 = new BigInteger("0");
                System.out.println(i==i1);//false
                System.out.println(i.equals(i1));//true

只需查看 method and the constructor.

的文档

public static BigInteger valueOf(long val)
Returns a BigInteger whose value is equal to that of the specified long. This "static factory method" is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers.

Parameters: val - value of the BigInteger to return.
Returns: a BigInteger with the specified value.

BigInteger(String val)
Translates the decimal String representation of a BigInteger into a BigInteger.

它们都以 BigInteger 的引用结束,其值为 0

  1. valueOf 是静态的,因此您不必为了获取值而创建对象。
  2. 如果调用构造函数,那么每次都会得到一个新对象。