Feasible way to avoid instanceof in equals method?

依然范特西╮ 提交于 2020-12-26 09:26:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!