Weird error
Brought to you by:
fgiust
I have run into a strange problem: when running this basic Java class I get always false although is should be true. Commons-lang 2.2, commonclipse 1.3.0
Am I missing something here?
Thanks in advance
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class Dummy {
static String NAME = "test"; public static void main(String[] args) { Dummy d1 = new Dummy(NAME); Dummy d2 = new Dummy(NAME); System.out.println(d1.equals(d2)); } private String name; public Dummy(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean equals(Object object) { if (!(object instanceof Dummy)) { return false; } Dummy rhs = (Dummy) object; return new EqualsBuilder().appendSuper(super.equals(object)).append( this.name, rhs.name).isEquals(); } public int hashCode() { return new HashCodeBuilder(-202685193, -95195117).appendSuper( super.hashCode()).append(this.name).toHashCode(); }
}
Logged In: NO
This is because the EqualsBuilder.appendSuper() is appending the super.equals() method. Your class' super is Object. Object.equals() compares the references and returns true only if the objects are the same. Remove the appendSuper() from the EqualsBuilder where the class doesn't extend anything (except, of course, Object).
While not as harmful, you should likewise remove the HashCodeBuilder.appendSuper() where the super is Object.