HashSet contains() method(HashSet contains() 方法)
问题描述
我执行了下面的代码,发现输出是 false
.
I executed below code and found the output was false
.
import java.util.Set;
import java.util.HashSet;
public class Name {
private String first, last;
public Name(String first, String last) {
this.first = first;
this.last = last;
}
public boolean equals(Object o) {
if (!(o instanceof Name))
return false;
Name n = (Name) o;
return n.first.equals(first) && n.last.equals(last);
}
public static void main(String[] args) {
Set<Name> s = new HashSet<Name>();
s.add(new Name("Donald", "Duck"));
System.out.println(s.contains(new Name("Donald", "Duck")));
}
}
我想知道它的行为方式以及为什么输出为 false
.
I want to know how it behaves and why output is false
.
推荐答案
您还需要重写 hashCode()
方法以及 equals()
.这两种方法都用于 HashSet
的正确功能,因此如果您将 class
作为key
,否则 Object
类的 hashCode()
正在被使用,没有两个不同的 objects
可以被视为相同因为它们的 hashCode()
总是不同的,并且在 contains()
的情况下肯定会返回 false
.
You need to override hashCode()
method also along with equals()
. Both the methods are used for proper functionality of HashSet
, so must be overriden in a user-defined class if you are making that class
as a key
, else hashCode()
of Object
class is getting used and no two different objects
can be considered as same as their hashCode()
would always be different, and will for sure return false
always in the case of contains()
.
这篇关于HashSet contains() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:HashSet contains() 方法


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