HashSet retainAll使用接口 [英] HashSet retainAll using interface

查看:1770
本文介绍了HashSet retainAll使用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,我尝试使用 HashSet.retainAll()函数。

I have some code where I try to use the HashSet.retainAll() function.

在下面的示例代码中, HashSet 包含接口 IPerson ,但是对象 Person 中的equals函数从未达到。我甚至试图揭露接口中的equals函数和其他几个事情。我觉得我已经尝试了一切。我如何使 retainAll()使用我实现的等函数?

In the example code below, the HashSet contains the interface IPerson, but the equals functions in object Person is never reached. I have even tried to expose the equals function in the interface and several other things. I feel I have tried everything. How can I make retainAll() use my implemented equal function?

class Person implements IPerson {
  private String name;
  public Person(String name){
    this.name = name;
  }

  @Override
  public boolean equals(Object obj){
    System.out.println("calling equals");
    return super.equals(Object obj);
  }

}

HashSet<IPerson> persons1 = new HashSet<IPerson>();
persons1.add(new Person("Jane"));
persons1.add(new Person("Joel"));
persons1.add(new Person("Joe"));

HashSet<IPerson> persons2 = new HashSet<IPerson>();
persons2.add(new Person("Jane"));
persons2.add(new Person("Joel"));

persons1.retainAll(persons2);
// expect sysout from Person.equals()

System.out.println(persons1.size());
// prints 0


推荐答案

覆盖 hashCode ,因为哈希集使用哈希码找到正确的'bucket',并且只有在它找到一些东西后才调用equals。这就是为什么你的equals方法从未被调用。 (如果你不重写hashcode方法,它会给每个新对象一个不同的hashcode,所以即使你调用 new Person(name)两次同名他们不会有相同的哈希码)

You need to override hashCode because the hashset uses the hashcode to find the right 'bucket' first and only calls equals after it finds something in it. That's why your equals method is never called. (if you don't override the hashcode method, it gives every new object a different hashcode, so even if you call new Person("name") twice with the same name they won't have the same hashcode)

这篇关于HashSet retainAll使用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆