I often use apache HashCodeBuilder and EqualsBuilder for object equality using reflection, but recently I a colleague told me that using reflection may cause a huge performance hit if the entity contains lots of properties. Worried that I may be using a wrong implementation, my question is, which of the following approach would you prefer? And why?
public class Admin {
private Long id;
private String userName;
public String getUserName() {
return userName;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Admin)) {
return false;
}
Admin otherAdmin = (Admin) o;
EqualsBuilder builder = new EqualsBuilder();
builder.append(getUserName(), otherAdmin.getUserName());
return builder.isEquals();
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
builder.append(getUserName());
return builder.hashCode();
}
}
Vs.
public class Admin {
private Long id;
private String userName;
public String getUserName() {
return userName;
}
@Override
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o, Arrays.asList(id));
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, Arrays.asList(id));
}
}
Of course the second option is more elegant and simple. But if you are concerned about performance you should go for first approach. Second method also fails if a security manager is running.
I would go for the first option if I was in your situation.
Also there is a mistake in your first approach in generating hashCode:
It should be
builder.toHashCode()instead of
builder.hashCode(). The latter returns hashcode builder object’s hash code.