实体的等号()无法在HashSet中正常工作

时间:2014-08-27 10:42:59

标签: java hashset equality

你可以给我一个想法,当它的实体被添加到HashSet时,mhy equals()在POJO中无法正常工作吗?我检查并hascode()正常工作,因为为具有相等字段的实体返回相同的哈希码。但是在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;
    }
}

2 个答案:

答案 0 :(得分:1)

result = 31 * result + clientID.hashCode();

我认为使用这行代码时,两个对象的hashCode不一样。尝试删除此行并测试

答案 1 :(得分:0)

谢谢您的建议,但我意识到我的错误。我没有说明应用程序是使用Hibernate将对象保存到数据库。在特定的Hibernate会话期间,对象在HashSet中添加。当我向已经在DB中的对象添加一个相等的对象时,它会在新的Hibernate会话中使用新的空HashSet。