如何在Java中使用equals方法?在JUnit中,我正在測試以確定兩個初始化爲相等的值是否相同,並聲明它們是相同的,但我的測試失敗。我確保檢查傳入的對象是另一個對象的一個實例,但我不確定爲什麼我的測試失敗。在Java中測試相等性
@Test
public void testEqualityOnBillSimple()
{
Date d1 = new Date(3,4,2020);
Money m1 = new Money(10);
Bill b1 = new Bill(m1, d1, "fred");
Bill b2 = new Bill(m1, d1, "fred");
assertTrue(b1.equals(b2));
}
public boolean equals (Object toCompare) {
try {
if (toCompare instanceof Bill) {
Bill that = (Bill) toCompare;
return this.amount.equals(that.amount) &&
this.dueDate.equals(that.dueDate) &&
this.paidDate.equals(that.paidDate) &&
this.originator.equals(that.originator);
}
} catch (Exception e) {
}
return false;
}
創建者是表示帳單正在付款的字符串。在這種情況下,它是Fred –
你重寫了'equals()'方法和'hashcode()'嗎? –
對不起,我還不熟悉hashcore –