Let's suppose I have class User
:
public class User {
private Long id;
private String name;
private Integer age;
private BigDecimal account;
// other fields, getters and setters
}
Is it proper to override the equals
method as follows?
@Override
public boolean equals(Object ob) {
if (ob == null) {
return false;
}
if (this == ob) {
return true;
}
if (ob instanceof User) {
User other = (User) ob;
return this.id.equals(other.getId());
}
return false;
}
It turns out that the uniqueness of an object is determined only by its ID. But in my application, id
is always unique. It's provided at the database. Is my equals
implementation competent enough to account for this? Or is this not best practice?
Of course I understand that in this case the hashCode
implementation should be the following:
@Override
public int hashCode() {
return id.intValue();
}