重写equals方法

重写equals方法,同时也要重写hashcode方法。

对象相等时,hashcode一定要相等。hashcode相等时,对象不一定相等。

以下是一个例子:

@Override
public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    UsernamePasswordCredentials that = (UsernamePasswordCredentials) o;

    if (password != null ? !password.equals(that.password) : that.password != null) return false;
    if (username != null ? !username.equals(that.username) : that.username != null) return false;

    return true;
}

 

@Override
public int hashCode() {
int result = username != null ? username.hashCode() : 0;
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}

这种17和31散列码的想法来自经典的Java书籍——《Effective Java》第九条

 

  1. @Override

  2. public int hashCode() {

  3. int result = 17;

  4. result = 31 * result + name.hashCode();

  5. result = 31 * result + age;

  6. result = 31 * result + passport.hashCode();

  7. return result;

  8. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值