【问题标题】:How to check if object already exists in HashSet? [duplicate]如何检查HashSet中是否已经存在对象? [复制]
【发布时间】:2017-12-04 19:19:11
【问题描述】:

这个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")));

是的

但是当我在 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")));

hSet 打印显示:

[id: 222name: 指环王]

我看不出在列表中添加新整数或添加新电影对象有什么不同。那么为什么我的示例不起作用?

//编辑。

如果有人正在寻找一个好的参考,this helped me out

【问题讨论】:

  • Movie 是否正确实现了equals()hashCode()
  • 造成这种差异的原因是Integer会覆盖hashCodeequals,而Movie不会。
  • 因为要在 Hashing thingy 中正常工作,你的类 Movie 必须实现 hashCode()。在那里实现equals()也是一件好事。 Integer 确实覆盖了这两个方法,而您的类很可能不会。
  • 哦,是的,我忘记了。谢谢,我去看看。

标签: java set


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2018-01-29
    • 2017-04-27
    • 2017-02-24
    • 1970-01-01
    相关资源
    最近更新 更多