Thursday, May 16, 2013

Using Eclipse to generate hashCode() and equals()

Right-click at the selected file, choose Source-> generate hashCode() and equals()
Then you can choose which attributes uniquely identify the object and then Eclipse generates hashCode() and equals() implementation like this:

/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((code == null) ? 0 : code.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof OtherObject))
return false;
OtherObject other = (OtherObject) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
return true;
}

No comments:

Post a Comment