我有以下代码:

public class MyElement {
    String name;
    String type;

    MyElement(String name, String type) {
        this.name = name;
        this.type = type;
    }
}

public class Test {

    public static void main(String[] args) {
        Set<MyElement> set = new HashSet<MyElement>();
        set.add(new MyElement("foo", "bar"));
        set.add(new MyElement("foo", "bar"));
        set.add(new MyElement("foo", "bar"));
        System.out.println(set.size());
        System.out.println(set.contains(new MyElement("foo", "bar")));
    }
}

当执行时返回:
3

false

我本来希望结果是1和true。为什么我的元素没有被识别为相同,我该如何纠正?
谢谢,
韦恩

最佳答案

您需要根据常规契约(Contract)在MyElement上实现equals(Object o)hashCode()。如果没有Set.contains(),它将使用默认的实现来比较对象的内存地址。由于要在contains调用中创建MyElement的新实例,因此它会返回false。

09-05 08:34
查看更多