2015-12-16 75 views
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)); 
    } 

我在這裏錯過了重要的東西嗎?

+1

您正在比較'equals'方法中的整數引用(不提及潛在的'ClassCastException')。使用'int'或'Integer#equals()'。 –

+0

是有道理的。完全錯過了這一點。 – Anurag

回答

1

而不是比較Integer對象引用:

return (this.accountNumber == account.getAccountNumber() && this.authPin == account.getAuthPin() 
     && this.transactionPin == account.getTransactionPin()); 

因爲,Integer對象引用不等於,例如此斷言失敗:

// different identities -> this assertion fails 
assert new Integer(7) == new Integer(7); 

使用.equals

return (Objects.equals(this.accountNumber, account.getAccountNumber()) 
     && Objects.equals(this.authPin, account.getAuthPin()) 
     && Objects.equals(this.transactionPin, account.getTransactionPin())); 

如果字段保證永遠null,那麼他們的類型更改爲int

private int accountNumber; 
private int authPin; 
private int transactionPin; 

那麼你不需要改變equals實施好,因爲它是。

相關問題