gpt4 book ai didi

java - 如何检查HashSet中是否已经存在对象?

转载 作者:行者123 更新时间:2023-11-30 02:18:15 25 4
gpt4 key购买 nike

这个example让它看起来很简单:

HashSet<Integer> hSet = new HashSet<Integer>();

hSet.add(new Integer("1"));
hSet.add(new Integer("2"));
hSet.add(new Integer("3"));

System.out.println(hSet.contains(new Integer("3")));

true

但是当我在 Movie 对象上使用它时(我想检查):

Set<Movie> hSet = new HashSet<Movie>();

hSet.add(new Movie(222, "Lord of the Rings", "something"));
System.out.println(hSet);

System.out.println(hSet.contains(new Movie(222, "Lord of the Rings", "something")));

false

hSet 打印显示:

[id: 222name: Lord of the Rings]

我没有看到添加新整数或向列表添加新电影对象有什么区别。那么为什么我的示例不起作用?

//编辑。

如果有人正在寻找好的引用,this helped me out .

最佳答案

您需要重写 Movie 类中的 hashcodeequals 方法。

在哈希集中,每当我们添加对象时,在添加对象之前,它都会通过覆盖哈希码来检查对象的哈希码值如果计算出的 hashcode 值在集合中已经可用,那么它将调用 equals 方法并检查我们要添加的对象是否与集合中已经可用的对象相等。如果对象相等,则不会将其添加到集合中,否则它将将该对象添加到集合中。

关于java - 如何检查HashSet中是否已经存在对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47640445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com