arshajii
arshajii

Reputation: 129537

Feasible way to avoid instanceof in equals method?

Many people don't like to use instanceof, but I find that in many cases we have few other options when it comes to the equals method. Take a look at the class below:

class A {   
    int n;
    public A(int n) { this.n = n; }

    @Override
    public boolean equals(Object o) {
        return false;
    }

    public boolean equals(A o) {
        return n == o.n;
    }   
}

I've never seen something like this done, but could it serve as a replacement for having to use instanceof to test if an Object is an A? Or are there other problems that I'm not thinking of?

Upvotes: 2

Views: 579

Answers (3)

Allen Parslow
Allen Parslow

Reputation: 209

This block of code is overloading not overriding equals. Also don't forget to check for o == null. Alternates to instanceof include getClass().equals(other.getClass()) and using A.isAssignableFrom(other.getClass())

Upvotes: 0

Dan D.
Dan D.

Reputation: 32391

The collections, Swing components and other classes that use equals will still call the equals(Object o) version and that will return false always.

The example will work when explicitly calling the equals(A o) method only.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533660

could it serve as a replacement for having to use instanceof to test if an Object is an A?

No. This is because the method called is chosen staticly i.e. only equals(object o) will be called in most situations.

You can write

@Override
public boolean equals(Object o) {
    return o instanceof A && n == ((A) o).n;
}

Upvotes: 8

Related Questions