重写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》第九条
-
@Override
-
public int hashCode() {
-
int result = 17;
-
result = 31 * result + name.hashCode();
-
result = 31 * result + age;
-
result = 31 * result + passport.hashCode();
-
return result;
-
}