Skip to main content

Entity Equals

Posted by evanx on June 28, 2007 at 11:01 AM EDT

Let's look at neatening up those messy equals() and hashCode() methods in our entities.


Code Snippet

public class Feed {
    private int id;
    private String uri;
    ...
    private Comparable[] values() {
        return new Comparable[] {id, uri};
    }
    
    public boolean equals(Object object)  {
        if (object instanceof Feed) {
            Feed feed = (Feed) object;
            return typeHelper.equals(values(), feed.values());
        }
        return false;
    }
    
    public int hashCode() {
        return typeHelper.hashCode(values());
    }
}    

where we implement a values() method to return an array of our IDs et al for hashCode() and equals(), and utilise a helper class.