[英]How do define my own element class for use with Set
I have the following code: 我有以下代码:
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")));
}
}
which when executed comes back with: 执行时返回:
3
false
I would have expected the result to be 1 and true. 我原以为结果是1而且是真的。 Why are my elements not being recognised as being the same and how do I rectify this?
为什么我的元素不被认为是相同的,我该如何纠正? Thanks, Wayne.
谢谢,韦恩。
You need to implement equals(Object o)
and hashCode()
on MyElement per the general contract. 您需要根据常规协定在MyElement上实现
equals(Object o)
和hashCode()
。 Absent that Set.contains()
will use the default implementation which compares the memory address of the objects. 缺少
Set.contains()
将使用比较对象的内存地址的默认实现。 Since you're creating a new instance of MyElement in the contains call it comes back as false. 由于您在包含调用中创建了一个新的MyElement实例,因此它返回false。
You should override an equals(MyElement me) function. 你应该覆盖一个equals(MyElement me)函数。 Equals returns a boolean
Equals返回一个布尔值
Otherwise, you are checking that two items are the same instance of an object, not that their internal content is the same. 否则,您正在检查两个项目是否是对象的相同实例,而不是它们的内部内容是相同的。
MyElement(String name, String type) {
this.name = name;
this.type = type;
}
public boolean Equals<MyElement>(MyElement me) {
return this.name.equals(me.name) && this.type.equals(me.type);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.