【问题标题】:contains() method in List not working as expectedList 中的 contains() 方法未按预期工作
【发布时间】:2015-04-01 12:05:04
【问题描述】:

contains()方法的api说

"如果此列表包含指定元素,则返回 true。更正式地说,当且仅当此列表包含至少一个元素 e 满足 (o==null ? e==null : o.equals (e))。 "

我在课堂上覆盖了equals() 方法,但contains() 在我检查时仍然返回false

我的代码

class Animal implements Comparable<Animal>{
    int legs;
    Animal(int legs){this.legs=legs;}
    public int compareTo(Animal otherAnimal){
        return this.legs-otherAnimal.legs;
    }
    public String toString(){return this.getClass().getName();}

    public boolean equals(Animal otherAnimal){
        return (this.legs==otherAnimal.legs) && 
                (this.getClass().getName().equals(otherAnimal.getClass().getName()));
    }

    public int hashCode(){
        byte[] byteVal = this.getClass().getName().getBytes();
        int sum=0;
        for(int i=0, n=byteVal.length; i<n ; i++)
            sum+=byteVal[i];
        sum+=this.legs;
        return sum;
    }

}
class Spider extends Animal{
    Spider(int legs){super(legs);}
}
class Dog extends Animal{
    Dog(int legs){super(legs);}
}
class Man extends Animal{
    Man(int legs){super(legs);}
}

请原谅课程背后的糟糕概念,但我只是在测试对我的概念的理解。

现在当我尝试这个时,它会打印 false,即使 equals 被覆盖

List<Animal> li=new ArrayList<Animal>();
Animal a1=new Dog(4);
li.add(a1);
li.add(new Man(2));
li.add(new Spider(6));

List<Animal> li2=new ArrayList<Animal>();
Collections.addAll(li2,new Dog(4),new Man(2),new Spider(6));
System.out.println(li2.size());
System.out.println(li.contains(li2.get(0))); //should return true but returns false

【问题讨论】:

  • 蜘蛛有 8 条腿 :)

标签: java collections java-collections-api


【解决方案1】:

您重载了equals 而不是覆盖它。要覆盖Objectequals 方法,必须使用相同的签名,这意味着参数必须是Object 类型。

改为:

@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()));
}

【讨论】:

  • 请注意,当您打算覆盖函数时使用@Override 注释将有助于防止此类错误。
【解决方案2】:

作为JLS-8.4.8.1 specify

在类 C 中声明的实例方法 m1 覆盖另一个实例 方法 m2,在类 A 中声明,如果满足以下所有条件:

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.

签名必须相同才能覆盖在您的情况下被忽略的那个!!!

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 2018-10-10
    • 2018-11-15
    • 2014-09-10
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多