Monday, February 6, 2012

Writing your own equals and hashCode method in Java

Writing your own equals and hashCode method in Java:

Sometime in application, we need to use our own equals() method to validate two objects for equality
rather than being dependent on Object's class.
Same way we need to generate hashCode() using our own methods, a sample is given below:

private String id ;
public CustomClass(String id){
    this.id = id ;
}
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public boolean equals(Object object){
    boolean isEqual = false ;
    if (object!=null){
        if(object instanceof CustomClass){
            String otherId = ((CustomClass)object).getId() ;
            if (otherId!=null){
                isEqual = otherId.equalsIgnoreCase(id) ;
            }
            else {
                isEqual = this == object ;                     
            }
        }
    }
            return isEqual ;
}
public int hashCode(){
            return id!=null ? id.hashCode() : super.hashCode() ;
}
=========================================================
//Another example:
public class CustomClass implements Serializable {

@Override
public boolean equals(Object obj) {
        if (obj == null)
            return false;
        CustomClass target = (CustomClass) obj;

        if (target.fileName == this.fileName && target.urlMapping == this.urlMapping 
                && (target.urlMapping != null && target.urlMapping.equals(this.urlMapping))) {
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        int hashcode = 7;
        hashcode = (hashcode << 5) + (this.fileName == null ? 0 : this.fileName.hashCode());
        hashcode = (hashcode << 5) + (this.urlMapping == null ? 0 : this.urlMapping.hashCode());
        return hashcode;
    }
}
=========================================================

No comments:

Post a Comment