0
我有銀行賬戶的樣本Java類:@overriding的equals()和hashCode()的Java類
public class Account {
private Integer accountNumber;
private Integer authPin;
private Integer transactionPin;
public Account(Integer accountNumber, Integer authPin, Integer transactionPin) {
this.accountNumber = accountNumber;
this.authPin = authPin;
this.transactionPin = transactionPin;
}
public Integer getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(Integer accountNumber) {
this.accountNumber = accountNumber;
}
public Integer getAuthPin() {
return authPin;
}
public void setAuthPin(Integer authPin) {
this.authPin = authPin;
}
public Integer getTransactionPin() {
return transactionPin;
}
public void setTransactionPin(Integer transactionPin) {
this.transactionPin = transactionPin;
}
@Override
public String toString() {
return accountNumber + "," + authPin + "," + transactionPin;
}
@Override
public boolean equals(Object obj) {
Account account = (Account) obj;
return (this.accountNumber == account.getAccountNumber() && this.authPin == account.getAuthPin()
&& this.transactionPin == account.getTransactionPin());
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return Objects.hashCode(this.getAccountNumber());
}
}
由於可以從代碼片段中可以看出,我已經重寫的equals()和hashCode( ) 方法。但是當我試圖使用jUnit做一個簡單的斷言檢查時,它是失敗的:
public class TestFileIO {
Account account;
@Before
public void setUp() throws Exception {
account = new Account(7, 2708, 2708);
}
@Test
public void testReadTransactionFile() {
assertEquals(account, new Account(7, 2708, 2708));
}
我在這裏錯過了重要的東西嗎?
您正在比較'equals'方法中的整數引用(不提及潛在的'ClassCastException')。使用'int'或'Integer#equals()'。 –
是有道理的。完全錯過了這一點。 – Anurag