将HashSet与用户类Employee一起使用

Abu*_*kar 3 java equals set hashcode hashset

我知道这听起来是一个非常愚蠢的问题,但是在我所知道的HashSet以及在执行下面代码时看到的内容后,我感到困惑.

我有一个Employee类如下(只保留相关的代码段):

public class Employee {
    //assume it has 3 variable name(String),salary(double) and id(int)
    //assume the constructor, getter-setters are there 

    //following is my equals and hashCode implementation
    public boolean equals(Employee e){
        return name.equals(e.name);
    }

    public int hashCode(){
        return id;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我有以下代码使用HashSet:

Employee e1  = new Employee("Abc", 2.0, 1);
Employee e2  = new Employee("abc", 3.0, 4);
Employee e3  = new Employee("XYZ", 4.0, 3);
Employee e4  = new Employee("Mno", 5.0, 2);
Employee e5  = new Employee("Abc", 77.0, 1);

Set<Employee> sEmp = new HashSet<Employee>();
sEmp.add(e1);
sEmp.add(e2);
sEmp.add(e3);
sEmp.add(e4);
sEmp.add(e5);

for(Employee e : sEmp){
    System.out.println(e);
}
Run Code Online (Sandbox Code Playgroud)

所以我将所有对象数据打印在我的控制台上:

Abc 77.0 1
Abc 2.0 1
Mno 5.0 2
XYZ 4.0 3
abc 3.0 4
Run Code Online (Sandbox Code Playgroud)

AFAIK,该套装不允许重复,这个复制品将被检查equals(如果我错了,请纠正我).

另外,HashSet使用the hashCode,所以在上面的例子中,它不应该添加对象e5.但它成功地将该元素添加到集合中.这困惑了我.

(如果我错过了标准和所有这些东西,请忽略,我试图理解概念/实现).

编辑:这听起来可能是一个愚蠢的问题,但我正在准备认证,并试图看看这些东西是如何工作的.

Sot*_*lis 7

你正在超载equals而不是覆盖它.其参数应为类型Object.

但是你hashCode正在检查id时间equals正在检查name.它们应该由相同的属性构成.