Java 使用接口的HashSet-retainal

Java 使用接口的HashSet-retainal,java,collections,equals,Java,Collections,Equals,我有一些代码试图使用HashSet.retainal()函数 在下面的示例代码中,HashSet包含接口IPerson,但对象Person中的equals函数永远无法到达。我甚至尝试在接口中公开equals函数和其他一些东西。我觉得我什么都试过了。如何使retainAll()使用实现的相等函数 class Person implements IPerson { private String name; public Person(String name){ this.name =

我有一些代码试图使用
HashSet.retainal()
函数

在下面的示例代码中,
HashSet
包含接口
IPerson
,但对象
Person
中的equals函数永远无法到达。我甚至尝试在接口中公开equals函数和其他一些东西。我觉得我什么都试过了。如何使
retainAll()
使用实现的相等函数

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
class-Person实现IPerson{
私有字符串名称;
公众人物(字符串名称){
this.name=名称;
}
@凌驾
公共布尔等于(对象obj){
System.out.println(“调用等于”);
返回super.equals(objectobj);
}
}
HashSet persons1=新的HashSet();
人员1.添加(新人员(“简”);
人员1.添加(新人员(“Joel”);
人员1.添加(新人员(“Joe”));
HashSet persons2=新的HashSet();
人员2.添加(新人员(“简”);
人员2.添加(新人员(“Joel”);
人员1.保留人员(人员2);
//期望Person.equals()提供sysout
System.out.println(persons1.size());
//打印0

<代码> >名称>代码>检查<代码>相等< /代码>,并将其包含在计算<代码> hash码< /代码>中,也请确保遵循

< p>您需要考虑<代码>名称<代码>检查“代码>相等< /代码>,并将其包含在计算<代码> hash码< /代码>中,还要确保您遵循

您需要重写。
hashCode
,因为hashset首先使用hashCode查找正确的“bucket”,只有在找到其中的内容后才调用equals。这就是为什么永远不会调用equals方法。(如果不重写hashcode方法,它会为每个新对象提供不同的hashcode,因此即使您使用相同的名称调用两次
newperson(“name”)
,它们也不会有相同的hashcode)

您需要重写
hashCode
,因为hashset首先使用hashCode来查找正确的“bucket”,只有在找到其中的内容后才调用equals。这就是为什么永远不会调用equals方法。(如果不重写hashcode方法,它会给每个新对象一个不同的hashcode,因此即使您使用相同的名称调用
newperson(“name”)
两次,它们也不会有相同的hashcode)

什么是
super.equals(object obj)正在做什么<代码>私人名称是另一个。。。请至少注意发布可编译代码。什么是
super.equals(objectobj)正在做什么<代码>私人名称是另一个。。。请至少注意发布可编译的代码。正如提示:您可以通过使用Eclipse->Source->Generate hashcode()和equals()轻松创建这两个方法。正如提示:您可以通过使用Eclipse->Source->Generate hashcode()和equals()轻松创建这两个方法。是的,问题确实是hashcode,另外(显然)必须考虑病例敏感性。即
返回getName().toLowerCase().hashCode()是的,问题实际上是哈希代码,另外(显然)必须考虑大小写敏感度。即
返回getName().toLowerCase().hashCode()