问题
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?
回答1:
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;
}
回答2:
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.
回答3:
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())
来源:https://stackoverflow.com/questions/13497144/feasible-way-to-avoid-instanceof-in-equals-method