Thursday, September 15, 2011

equals, hashCode, and toString with Apache Commons

Lets now play a little bit with Apache Commons EqualsBuilder, HashCodeBuilder, and ToStringBuilder.

ToStringBuilder

When we print an object to console, something not meaningful like [Ljava.lang.String;@a90653 will be printed. If we have an entity bean, most likely we prefer printing all of its properties in a formatted string to previous string. To achieve that, we can use ToStringBuilder class in Apache Commons Lang library.

public class MyBean {

private String name;
private String address;
private String email;

@Override
public String toString() {
return new ToStringBuilder(this).append("name", name).append("address", address).append("email", email).build();
}

}

And the result will be MyBean@a62fc3[name=Al Pacino,address=Surabaya,email=gmail].

EqualsBuilder

When we want to compare two entity beans, most likely we want to compare by properties. If both entity holds same properties, they are equal. We can use EqualsBuilder to do this.

@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}

if((obj == null) || (obj.getClass() != this.getClass())) {
return false;
}

MyBean target = (MyBean) obj;
return new EqualsBuilder().append(this.name, target.name).append(this.address, target.address).append(this.email, target.email).isEquals();
}

HashCodeBuilder

Note that we must override the Object.hashCode() if we override Object.equals(). We can use HashCodeBuilder to create hash code for an object.

@Override
public int hashCode() {
return new HashCodeBuilder().append(this.name).append(this.address).append(this.email).toHashCode();
}

0 comments:

 

©2009 Stay the Same | by TNB