如何定义我自己的元素类以用于Set [英] How do define my own element class for use with Set

查看:76
本文介绍了如何定义我自己的元素类以用于Set的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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而且是真的。为什么我的元素不被认为是相同的,我该如何纠正?
谢谢你,
Wayne。

I would have expected the result to be 1 and true. Why are my elements not being recognised as being the same and how do I rectify this? Thanks, Wayne.

推荐答案

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

You need to implement equals(Object o) and hashCode() on MyElement per the general contract. Absent that Set.contains() will use the default implementation which compares the memory address of the objects. Since you're creating a new instance of MyElement in the contains call it comes back as false.

这篇关于如何定义我自己的元素类以用于Set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆