contains() method in List not working as expected

前端 未结 2 1006
鱼传尺愫
鱼传尺愫 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()));
    }
    

提交回复
热议问题