Sunday, September 7, 2008

Generating same hashcode for similiar objects

Always override hashCode method if you are overriding the equals method of a java class. A POJO containing the same values in the properties can generate different hashCodes by default. If you need a way to generate the same hashCodes for POJO’s with same properties, instead of writing your own logic like adding properties or any other method, consider using apache’s commons-lang class HashCodeBuilder. This is specially worth considering if the objects are being added to data structures that use hashing mechanism for storing objects e.g. HashSet, HashMap, etc.

@Override  
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}

No comments:

Post a Comment