When to use identity comparison instead of equals?

Posted by maaartinus on Programmers See other posts from Programmers or by maaartinus
Published on 2012-10-05T21:00:17Z Indexed on 2012/10/05 21:52 UTC
Read the original article Hit count: 296

Filed under:
|

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?

© Programmers or respective owner

Related posts about object-oriented

Related posts about comparison