【问题标题】:Why BigInteger.ONE not equals to new BigInteger("1") in java? [duplicate]为什么 BigInteger.ONE 不等于 java 中的 new BigInteger("1")? [复制]
【发布时间】:2015-11-29 09:21:28
【问题描述】:

在 Java8 中使用 BigInteger 类时,我编写了这段代码

System.out.println(new BigInteger("1")==BigInteger.ONE);

理想情况下它应该打印 true,但它的输出是 false。为什么它的输出是假的?

【问题讨论】:

标签: java biginteger


【解决方案1】:
new BigInteger("1")==BigInteger.ONE

可以改写为

BigInteger bigint =new BigInteger("1");
BigInteger bigint2= BigInteger.ONE;

现在

System.out.println(bigint ==bigint2); //false

因为它们指向不同的引用。

== 检查引用。不是它们里面的价值。

您可以尝试使用 equals() 方法来检查它们的相等性。

【讨论】:

    【解决方案2】:

    因为您使用 == 而不是 .equals(yourNumberToBeCompared)

    你应该这样做:

    System.out.println(new BigInteger("1").equals(BigInteger.ONE));
    

    【讨论】:

      【解决方案3】:

      == 检查对象是否指向相同的引用,因此如果a = b 则条件a == b。建议仅对原始类型执行此操作。

      要检查对象的内容是否相同,请使用函数equals(Object otherObject)。例如:

      new BigInteger("1").equals(BigInteger.ONE); 
      

      这将返回true,因为两个对象的内容相同。使用== 将返回false,因为每个对象都有不同的引用。

      另一个例子是这样的:

      MyObject object1 = new MyObject(30);
      MyObject object2 = object1; //this will make them have the same reference
      
      // This prints true, as they have the same content.
      System.out.println(object1.equals(object2));
      
      // This will print true, as they point the same thing, because they have the same reference
      System.out.println(object1 == object2);
      
      // We can see they have the same reference because if we edit one's field, 
      // the other's one will change too.
      object1.number = 10;
      System.out.println(object1.number); // prints 10
      System.out.println(object2.number); // prints 10 too
      

      【讨论】:

        猜你喜欢
        • 2019-04-16
        • 2018-09-03
        • 1970-01-01
        • 2011-06-10
        • 2015-04-08
        • 2017-01-31
        • 2020-09-23
        • 2020-01-08
        • 2016-05-14
        相关资源
        最近更新 更多