根据documentation列表包含应该使用 equals()。意思是,如果对象内的值相同,它应该返回 true。但是,在下面的示例中 contains(Object) 的行为有所不同:
import java.util.ArrayList;
import java.util.List;
public class Dog{
private String name;
private int age;
private String colour;
public Dog(String name, int age, String colour){
this.name = name;
this.age = age;
this.colour = colour;
}
public static void main(String []args){
List<String> names = new ArrayList<>();
String name1 = "adam";
names.add(name1);
System.out.println(names.contains(new String("adam"))); //returns true
List<Dog> dogs = new ArrayList<>();
Dog fido = new Dog("fido", 2, "black");
dogs.add(fido);
System.out.println(dogs.contains(new Dog("fido", 2, "black"))); // returns false
}
}
为什么比较新的String对象时返回true,而比较新的Dog对象时则不返回true?
我知道我可以通过重写 contains(Object) 来解决这个问题,但很想知道为什么默认情况下这不起作用。
最佳答案
List<Dog> dogs = new ArrayList<>();
Dog fido = new Dog("fido", 2, "black");
dogs.add(fido);
System.out.println(dogs.contains(new Dog("fido", 2, "black")));
返回 false,因为 DOG 自定义类中未实现 Hashcode 和 Equals。 在java.lang.String类中,hashCode()方法也被重写,以便两个相等的字符串对象根据equals()方法将返回相同的哈希码值。
关于java - 为什么 List.contains(Object) 的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57277194/