gpt4 book ai didi

java - List 中的 contains() 方法未按预期工作

转载 作者:行者123 更新时间:2023-12-02 15:28:02 24 4
gpt4 key购买 nike

contains() 方法的 api 说

“如果此列表包含指定元素,则返回 true。更正式地说,当且仅当此列表包含至少一个元素 e 时,返回 true 使得 (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);}
}

请原谅类(class)背后的坏概念,但我只是在测试对我的概念的理解。

现在当我尝试这个时,它打印 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

最佳答案

您重载了 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()));
}

关于java - List 中的 contains() 方法未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29390340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com