When to use identity comparison instead of equals?
- by maaartinus
I wonder why would anybody want to use identity comparison for fields in equals, like here (Java syntax):
class C {
private A a;
public boolean equals(Object other) {
// standard boring prelude
if (other==this) return true;
if (other==null) return false;
if (other.getClass() != this.getClass()) return false;
C c = (C) other;
// the relevant part
if (c.a != this.a) return false;
// more tests... and then
return true;
}
// getter, setters, hashCode, ...
}
Using == is a bit faster than equals and a bit shorter (due to no need for null tests), too, but in what cases (if any) you'd say it's really better to use == for fields inside equals?