对象比较在HashSet中不起作用

时间:2017-09-14 07:32:16

标签: java collections hashset

我在员工类

中编写了equals和hashcode实现
public class Employee {

    private Integer eid;

    private String name;

    private Integer annualSalary; 

    private String location;

    public Employee(Integer eid, String name, Integer annualSalary, String location) {
        super();
        this.eid = eid;
        this.name = name;
        this.annualSalary = annualSalary;
        this.location = location;
    }

    //setter and getters

    @Override
    public boolean equals(Object obj) {
        Employee secondemp = (Employee) obj;

        boolean equalsComparison = this.getEid() == secondemp.getEid() 
                && this.getName().equals(secondemp.getName())
                && this.getAnnualSalary() == secondemp.getAnnualSalary() //this condition is returning as false
                && this.getLocation().equals(secondemp.getLocation()); 

        System.out.println("equals=>"+equalsComparison);

        return equalsComparison;
    }

    @Override
    public int hashCode() {
        int hash = 31;
        hash += this.getEid().hashCode();
        hash += this.getName().hashCode();
        hash += this.getAnnualSalary();
        hash += this.getLocation().hashCode();

        System.out.println("hashcode=>"+hash);
        return hash;
        //return super.hashCode();
    }

    @Override
    public String toString() {
        return ""+this.eid;
    }
}

在hashset类中添加相同的员工对象。

    private Set<Employee> employeeSet = new HashSet<>();   
employeeSet.add(new Employee(101, "Ankit Agarwal", 10001, "Uttar Pradesh"));
employeeSet.add(new Employee(101, "Ankit Agarwal", 10001, "Uttar Pradesh"));
employeeSet.add(new Employee(101, "Ankit Agarwal", 10001, "Uttar Pradesh"));
employeeSet.add(new Employee(101, "Ankit Agarwal", 10001, "Uttar Pradesh"));
employeeSet.add(new Employee(101, "Ankit Agarwal", 10001, "Uttar Pradesh"));

equals方法的比较不起作用。

但是,如果我将数据类型更改为基元,即 int ,那么比较工作正常。

在对它进行更多调试之后,这个条件在equals方法

上返回false
            && this.getAnnualSalary() == secondemp.getAnnualSalary() 

有什么建议吗?

0 个答案:

没有答案