Tuesday, February 10, 2009

Commons HashCodeBuilder

The class HashCodeBuilder enables a good hashCode method to be built for any class. It follows the rules laid out in the book Effective Java by Joshua Bloch. Writing a good hashCode method is actually quite difficult. This class aims to simplify the process.

All relevant fields from the object should be included in the hashCode method. Derived fields may be excluded. In general, any field used in the equals method must be used in the hashCode method.

public class LineItemId implements Serializable{

private static final long serialVersionUID = 1L;

private int orderId;

private int productId;

public int hashCode() {
return new HashCodeBuilder(17, 37).append(orderId).append(productId).toHashCode();

No comments:

Post a Comment