0

Convenient Way to override equals(), hashCode(), and toString() methods

Background

Two years ago, I used to override the equals() and hashCode() methods via Eclipse’s “Generate hashCode() and equals()…” feature. It proved to be a maintenance nightmare. Every time a new field is added to a class, these methods are updated to include the new instance variable. There is a convenient way to override these methods, toString() included. One that’ll not require subsequent changes when fields are added or remove from a class.

Software Environment

  • Windows 7 Professional SP1
  • Java 1.7 (1.7.0_67 – Windows x86)
  • Eclipse Luna
  • org.apache.commons┬ácommons-lang3 (v3.4)

Java Codes

Say you have an EmployeeDTO class:

Modify the class to:

Here, we used classes from Apache Commons Lang:

  1. ToStringBuilder
  2. EqualsBuilder
  3. HashCodeBuilder

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert