Override equals() and hashcode()
When ever equals() is overriden, so should hashcode() (see
Effective Java ).
Use the commons lang EqualsBuilder, HashCodeBuilder, ToStringBuilder for constructing these.
equals()
The equals method allow direct access to the instance variable of the object being compared to.
Direct access to the properties should be avoided where possible, instead the getter methods used.
This is important, since the object instance obj passed to equals might be a proxy object, not the
actual implementation that holds the persistent state (ie. when used through Hibernate etc).
/**
* override default equals implementation.
*
* @param obj
* to compare
* @return whether the two object are equal.
*/
public boolean equals(Object obj) {
//short cut for same reference
if (this == obj) {
return true;
} if (!(obj instanceof Column)) {
return false;
} Column o = (Column) obj;
return new EqualsBuilder()
.append(refCol, o.getRefCol())
.append(isVisible, o.isVisible())
.append(sortDir, o.getSortDir())
.append(name, o.name) // (1) direct access should be avoided
.isEquals();
}
Here at (1) o.name is permissable, but its convience method should be used ie. o.getName().
Eclipse plugin
Plugin allows generation of hashCode(), equals(), toString() and compareTo() using commons lang Builders.
http://commonclipse.sourceforge.net/index.html