初始化java.math.BigInteger

时间:2016-09-07 06:17:10

标签: java biginteger

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

BigInteger i = BigInteger.valueOf(0);

BigInteger i = new BigInteger("0");

他们是一样的吗?

5 个答案:

答案 0 :(得分:8)

他们最终都引用了BigInteger,其值为0,但它们的效果并不相同。特别是,由于valueOf是一个静态方法,它可以使用缓存,如果你调用它两次,则返回相同的引用:

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

这似乎不是保证,但鉴于documentation,它确实有点预期

  

返回BigInteger,其值等于指定long的值。这个"静态工厂方法"优先于(长)构造函数提供,因为它允许重用常用的BigIntegers。

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

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

答案 1 :(得分:5)

是的,在这种情况下,它们是相同的(如果用“相同”表示“相等的实例”),你也可以说BigInteger.ZERO

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

new BigInteger("12345678901234567890123456789012345")  // too long for long

答案 2 :(得分:3)

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

答案 3 :(得分:3)

只需查看methodconstructor的文档。

  

public static BigInteger valueOf(long val)
  返回一个BigInteger,其值等于指定long的值。这个"静态   工厂方法"优先于(长)构造函数提供   因为它允许重用经常使用的BigIntegers。

     

参数: val - 要返回的BigInteger的值   返回:具有指定值的BigInteger。

     

BigInteger(String val)
  将BigInteger的十进制字符串表示形式转换为BigInteger。

他们最终都引用了BigInteger,其值为0

  1. valueOf是静态的,因此您无需创建对象即可获取该值。
  2. 如果你调用构造函数,那么每次都会得到一个新对象。

答案 4 :(得分:1)

让我们做一个快速实验:

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

因此,确切地说:这里有两个相等的 BigInteger对象。 由于BigInteger构造函数只允许输入“整数”整数;对于valueOf()能够给你的所有值都是如此。

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