Wednesday, February 1, 2012

Overriding equals in Groovy

I was overriding equals method in for a Groovy class and got into StackOverflow error.




class ObjKey {
long id
String value

public boolean equals(Object obj) {
if (!(obj instanceof ObjKey)) {
return false;
}
if (this == obj) {
return true;
}
ObjKey rhs = (ObjKey) obj;
return new EqualsBuilder()
.append(id, rhs?.id)
.append(value, rhs?.value)
.isEquals();
}

public int hashCode() {
return new HashCodeBuilder()
.append(id)
.append(value)
.toHashCode();
}
}



I was getting stackoverflow at line: if (this == obj). Groovy's equals calls the equals method instead of comparing the reference.

I fixed it using bellow syntax: if (this.is(obj)). The corrected code looks like:


class ObjKey {
long id
String value

public boolean equals(Object obj) {
if (!(obj instanceof ObjKey)) {
return false;
}
if (this.is(obj)) {
return true;
}
ObjKey rhs = (ObjKey) obj;
return new EqualsBuilder()
.append(id, rhs?.id)
.append(value, rhs?.value)
.isEquals();
}

public int hashCode() {
return new HashCodeBuilder()
.append(id)
.append(value)
.toHashCode();
}
}

No comments:

Post a Comment