【问题标题】:Why does List.contains(Object) behaves differently? [duplicate]为什么 List.contains(Object) 行为不同? [复制]
【发布时间】:2019-12-08 04:08:17
【问题描述】:

根据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对象时不返回?

我知道我可能可以通过覆盖 contains(Object) 来解决这个问题,但很想知道为什么默认情况下这不起作用。

【问题讨论】:

  • 你需要重写Dog类中的equals方法
  • 因为String.equals()Dog.equals() 不同,Dog.equals() 继承自身份相等的Object.equals() (==)

标签: java list arraylist equals contains


【解决方案1】:
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 因为 Hashcode 和 Equals 未在 DOG 自定义类中实现。 在 java.lang.String 类中,hashCode() 方法也被覆盖,因此根据 equals() 方法,两个相等的字符串对象将返回相同的哈希码值。

【讨论】:

    猜你喜欢
    • 2014-05-15
    • 2016-06-16
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2014-03-07
    • 2018-11-03
    相关资源
    最近更新 更多