contains() method in List not working as expected

牧云@^-^@ 提交于 2019-12-02 00:52:58

You overloaded equals instead of overriding it. To override Object's equals method, you must use the same signature, which means the argument must be of Object type.

Change to:

@Override
public boolean equals(Object other){
    if (!(other instanceof Animal))
        return false;
    Animal otherAnimal = (Animal) other;
    return (this.legs==otherAnimal.legs) && 
           (this.getClass().getName().equals(otherAnimal.getClass().getName()));
}

As JLS-8.4.8.1 specify

An instance method m1, declared in class C, overrides another instance method m2, declared in class A , if all of the following are true:

C is a subclass of A.

The signature of m1 is a subsignature  of the signature of m2.

Either:

m2 is public, protected, or declared with default access in the same package as C, or

m1 overrides a method m3 (m3 distinct from m1, m3 distinct from m2), such that m3 overrides m2.

Signature Must be same to override which in your case is ignored !!!

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