您可以給我一個想法嗎?當它的實體添加到HashSet中時,equals()在POJO中無法正常工作?我檢查和hascode()正常工作,因爲具有相同字段的實體返回相同的哈希碼。但是相同的對象被添加到HashSet中。請看看下面的代碼:實體的equals()在HashSet中無法正常工作
@Entity
@Table(name = "account")
public class Account {
private int accountID;
private String accountNumber;
private float amount;
private String currency;
private Client clientID;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "account_id")
public int getAccountID() {
return accountID;
}
public void setAccountID(int accountID) {
this.accountID = accountID;
}
@Column(name = "account_number")
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
@Column(name = "amount")
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
@Column(name = "currency")
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "client_id")
public Client getClientID() {
return clientID;
}
public void setClientID(Client clientID) {
this.clientID = clientID;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Account)) return false;
Account account = (Account) o;
if (Float.compare(account.amount, amount) != 0) return false;
if (!accountNumber.equals(account.accountNumber)) return false;
if (!clientID.equals(account.clientID)) return false;
if (!currency.equals(account.currency)) return false;
return true;
}
@Override
public int hashCode() {
int result = accountNumber.hashCode();
result = 31 * result + (amount != +0.0f ? Float.floatToIntBits(amount) : 0);
result = 31 * result + currency.hashCode();
result = 31 * result + clientID.hashCode();
return result;
}
}
一個可能的問題是,在將其放入HashSet後,某個實體發生了更改 – talex 2014-08-27 10:45:54
提供可重現問題的示例代碼。 – 2014-08-27 10:47:00
'客戶'覆蓋'equals'和'hashcode'方法嗎? – pratZ 2014-08-27 10:47:53