A simple, standard and reusable way of creating toString, equals and hashcode methods in your classes/beans can be found in the jakarta commons.lang package:
import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; public class BaseBean { public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); } public int hashCode() { // EDIT: this hashCode-implementation seems to break Hibernate: // it throws a LazyInitializationException // return HashCodeBuilder.reflectionHashCode(this); // // using this implementation for now return new HashCodeBuilder(25, 71) // random odd numbers .append(this.getId()) // a field in BaseBean, not shown for brevity .append(super.hashCode()) // using the standard hashcode too .toHashCode(); } }
Mark your collections with the transient keyword and do not include them into the hash code.
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, false);
}
Regards,
Cyrill
On the StringBuffer vs “+” issue. Check out these sites:
old (2000)
newer (2003)
Or even this one . The compiler used also has an impact. I measured it and it checks out.
Using the StringBuffer or the “+” method depends on what you are doing. If you are appending in a loop use StringBuffer, if not the difference is neglectable. So when in doubt use StringBuffer I would say…
Be sure to use commons-lang version 2.0. Oracle JDeveloper ships with an older version which does not have the builder package, I spend a few frustrating moments figuring out what Ant was trying to tell me…
Using StringBuffer.append instead of + for efficiency reasons worked well for JDK 1.1. But the compiler is much better now.
This sequence String s = “a” + “b” + variable + “x”; is the same efficiency as using a StringBuffer.
I also like Rod Johnson’s approach, e.g.:
public String toString()
{
StringBuffer sb = new StringBuffer(getClass().getName() + ": ");
sb.append("Primary key=" + id + "; ");
sb.append("Surname='" + getSurname() + "'; ");
sb.append("Forename='" + getForename() + "'; ");
sb.append(" systemHashcode=" + System.identityHashCode());
return sb.toString();
}
Note the use of StringBuffer instead of using the “+” operator (efficiency!). I like the use of the apostrophes in particular, very useful in detecting leading or trailing white spaces!
But of course, if you have the avail over the Jakarta common’s lang package, the posted version is much less work!