I tend to write my equals method in Java as a one liner...
class Test {
private String a = "";
private Integer b = Integer.MIN_VALUE;
private Long c = Long.MIN_VALUE;
public Test(final String a, final Integer b, final Long c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public boolean equals(final Object obj) {
return obj instanceof Test && ((Test) obj).a.equals(this.a)
&& ((Test) obj).b.equals(this.b)
&& ((Test) obj).c.equals(this.c);
}
}
As you can see, in this approach I downcast the Object instance to Test instance many times. My question is, will it be optimised by the compiler so there will be a single downcast instead of three like if I wrote my equals method like this?
public boolean equals(final Object obj) {
if (obj instanceof Test) {
final Test test = (Test) obj;
return test.a.equals(this.a) && test.b.equals(this.b)
&& test.c.equals(this.c);
} else {
return false;
}
}
It is not a duplicate of the question in comment, because I am interested here in brevity of the implementation of the equals method (6 lines against 3) but not at cost of a performance degradation. In the other question the difference is one line.