How do define my own element class for use with Set(如何定义我自己的元素类以与 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 且为真.为什么我的元素不被认为是相同的,我该如何纠正这个问题?谢谢,韦恩.
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.
推荐答案
您需要根据通用合约在 MyElement 上实现 equals(Object o)
和 hashCode()
.如果没有 Set.contains()
将使用比较对象的内存地址的默认实现.由于您在 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 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何定义我自己的元素类以与 Set 一起使用


- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01