我遇到错误:
java.lang.AssertionError: expected: learning.java.advancedoop2.MyComplex<(2.0+10.0i)> but was: learning.java.advancedoop2.MyComplex<(2.0+10.0i)>
Expected :learning.java.advancedoop2.MyComplex<(2.0+10.0i)>
Actual :learning.java.advancedoop2.MyComplex<(2.0+10.0i)>
我现在正在处理MyComplex类,如3.1所示: http://www.ntu.edu.sg/home/ehchua/programming/java/J3f_OOPExercises.html#zz-2
这是相关代码的一部分:
package learning.java.advancedoop2;
public class MyComplex {
private double real = 0.0;
private double imag = 0.0;
public MyComplex() {
}
public MyComplex add(MyComplex right) {
this.imag += right.imag;
this.real += right.real;
return this;
}
}
我尝试进行测试,当我运行它们时,我遇到的错误是潜在的,这是我的测试代码的一部分:
@Test
public void add() {
MyComplex myComplexFirst = new MyComplex(1, 5);
MyComplex myComplexSecond = new MyComplex(1, 5);
MyComplex myComplexThird = new MyComplex(myComplexFirst.getReal() + myComplexSecond.getReal(), myComplexFirst.getImag() + myComplexSecond.getImag());
myComplexFirst.add(myComplexSecond);
MyComplex newComplex = myComplexFirst;
assertEquals(newComplex, myComplexThird);
}
答案 0 :(得分:2)
您是否在自定义类中覆盖了equals方法?
如果没有,默认行为是比较引用。这将解释您收到的错误消息。
这令人困惑,因为您已经覆盖了toString方法,该方法将两个实例显示为具有相同的值。
答案 1 :(得分:0)
您需要重写equals方法,以便Java知道如何比较两个MyComplex
对象。现在,它不知道您要基于real
和imag
的值来比较对象。
@Override
public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
// Check if o is an instance of MyComplex
if (!(o instanceof MyComplex)) {
return false;
}
// typecast o to MyComplex so that we can compare data members
MyComplex c = (MyComplex) o;
// Compare the data members and return accordingly
return Double.compare(real, c.getReal()) == 0
&& Double.compare(imag, c.getImag()) == 0;
}