contains() method in List not working as expected

前端 未结 2 977
鱼传尺愫
鱼传尺愫 2021-01-22 12:50

the api of contains() method says

\"Returns true if this list contains the specified element. More formally, returns true if and only if this list conta

相关标签:
2条回答
  • 2021-01-22 13:31

    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()));
    }
    
    0 讨论(0)
  • 2021-01-22 13:42

    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 !!!

    0 讨论(0)
提交回复
热议问题