Skip to main content

Be careful writing hashCode() methods when using HashCodeBuilder

I've blogged in the past about using the Apache Commons EqualsBuilder and HashCodeBuilder to write simpler equals() & hashCode() methods.

My colleague recently blogged about a potential pitfall when using this approach, I'll summarise his findings here:

Be VERY careful when you ask the HashCodeBuilder to generate the resulting hashcode value:

Make sure you call builder.toHashCode() rather than builder.hashCode()

The first correctly generates a hashcode value based on the objects that you have added to the builder, the second gives you the hashcode of the builder object itself - definitely not the value you would be expecting (and would be a sure fire way to lose your objects in a Collection)...

Technorati Tags: , , , ,