我正在编写一些代码来演示equals和hashcode,对于我的实现,我使用了用户示例:
public class User {
private String name;
private String pass;
//...
@Override
public boolean equals(Object obj) {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (obj.getClass() != this.getClass()) {
return false;
}
User rhs = (User) obj;
EqualsBuilder eb = new EqualsBuilder();
eb.append(this.getName(), rhs.getName());
//eb.append(this.getPass(), rhs.getPass());
return eb.isEquals();
}
@Override
public int hashCode() {
HashCodeBuilder hcb = new HashCodeBuilder(17, 37);
hcb.append(this.getName());
hcb.append(this.getPass());
return hcb.toHashCode();
}
//...
public static void main(String[] args) {
User u1 = new User("foo","foo1");
User u2 = new User("bar","bar1");
System.out.println(u1.equals(u2));
System.out.println(u1.hashCode() + " ?= " + u2.hashCode());
User u3 = new User("foo","foo1");
User u4 = new User("foo","bar1");
System.out.println(u3.equals(u4));
System.out.println(u3.hashCode() + " ?= " + u4.hashCode());
}
}
输出:
false
2128613651 ?= 2129111967
true
2128615478 ?= 2214545177
我认为我做错了,因为我的对象现在可以相等但具有不同的哈希码(我知道这很糟糕),但我想让我的用户只有在他们的名字也相等时才相等..而不是当他们有名称 AND 通过等于。
我怎样才能尊重约定并拥有我想要实现的目标?感谢您的帮助/澄清:)