# 为什么在Java中比较两个相同的对象时测试失败？

go评论55阅读模式

Why is the test failing when comparing two of the same objects in Java?

# 问题

``````@Test
P1 = new PolynomialImp("12x^2+5");
P2 = new PolynomialImp("16x^2+6");
Polynomial P4 = new PolynomialImp("28x^3+11");
assertTrue(P3.equals(P4));

}
``````

``````@Test
P1 = new PolynomialImp("12x^3+5");
P2 = new PolynomialImp("16x^3+6");
Polynomial P3 = new PolynomialImp("28x^3+11");
Polynomial P4 = new PolynomialImp("28x^3+11");
assertTrue(P3.equals(P4));
}
``````

I'm trying to make a polynomial calculator to learn how to code and as I'm testing it there's a part which fails when comparing two of the same objects which is not making any sense to me. See the following test unit that is failing.

``````@Test
P1 = new PolynomialImp(&quot;12x^2+5&quot;);
P2 = new PolynomialImp(&quot;16x^2+6&quot;);
Polynomial P4 = new PolynomialImp(&quot;28x^3+11&quot;);
assertTrue(P3.equals(P4));

}
``````

The thing is, it fails even when I change the tester to the following.

``````@Test
P1 = new PolynomialImp(&quot;12x^3+5&quot;);
P2 = new PolynomialImp(&quot;16x^3+6&quot;);
Polynomial P3 = new PolynomialImp(&quot;28x^3+11&quot;);
Polynomial P4 = new PolynomialImp(&quot;28x^3+11&quot;);
assertTrue(P3.equals(P4));
}
``````

Shouldn't it pass considering they are both created with the same variables?

# 答案1

`P3.equals(P4)`检查P3和P4是否为同一个对象的实例。您需要重写`equals`方法并相应地返回`true``false`

`P3.equals(P4)` checks whether P3 and P4 are the same instance of an object. You have to override the `equals` method to return `true` or `false` accordingly.

# 答案2

`equals()` 的默认实现仅在两个对象为同一对象时返回 true，因此仅在 P3.equals(P3) 的情况下返回 true，或者如果您执行以下操作：

``````P3 = new ...
P4 = P3;
P3.equals(P4); // true
``````

The default implementation of `equals()` is only true when both objects are the same object, so only for P3.equals(P3) or if you do

``````P3 = new ...
P4 = P3;
P3.equals(P4); // true
``````

If you need equivality based on the logic of your program (i.e. 2 polynomials are equal if they are initialized with the same string), you have to override the equals() methof of your class and implement that logic yourself.

• 本文由 发表于 2020年10月4日 17:49:19
• 转载请务必保留本文链接：https://go.coder-hub.com/64193164.html
• java
• unit-testing

go 61

go 90

go 62

go 53