我有一个用于银行帐户的示例 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));
}
我在这里遗漏了一些重要的东西吗?
最佳答案
而不是比较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
实现,就这样就好了。
关于java - Java 类中的 @overriding equals() 和 hashCode(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322678/