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

huangapple go评论54阅读模式
英文:

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

问题

我正在尝试制作一个多项式计算器,以学习编程。在我进行测试时,有一个部分在比较两个相同的对象时失败了,这对我来说毫无意义。请看下面的测试单元,它正在失败。

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

问题是,即使我将测试者更改为以下内容,它仍然失败。

@Test
public void testAddition() {
        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
public void testAddition() {
        P1 = new PolynomialImp("12x^2+5");
        P2 = new PolynomialImp("16x^2+6");
		Polynomial P3 = P1.add(P2);
		Polynomial P4 = new PolynomialImp("28x^3+11");
		assertTrue(P3.equals(P4));
		
	}

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

@Test
public void testAddition() {
        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));
	}

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

答案1

得分: 0

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

英文:

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

得分: 0

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

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

如果您需要基于程序逻辑的等同性(即,如果两个多项式使用相同的字符串进行初始化,则它们相等),您必须重写您的类的 equals() 方法并自行实现该逻辑。

英文:

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.

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

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定