This question already has answers here:
HashSet contains duplicate entries
                                
                                    (4个答案)
                                
                        
                2年前关闭。
            
        

在下面的代码中,我在哈希集中添加了5个具有相同数据的对象,并且我想消除具有重复数据的对象并打印不同的对象数据。

public static void main(String[] args) {
Employee emp1 = new Employee(1,"sandhiya","cse",22);
Employee emp2 = new Employee(1,"sandhiya","cse",22);
Employee emp3 = new Employee(1,"sandhiya","cse",22);
Employee emp4 = new Employee(1,"sandhiya","cse",22);
Employee emp5 = new Employee(1,"sandhiya","cse",22);
HashSet<Employee> emps = new HashSet<Employee>();
emps.add(emp1);
emps.add(emp2);
emps.add(emp3);
emps.add(emp4);
emps.add(emp5);
for(Employee e: emps){
    System.out.println(e.id + " "+e.name+" "+e.department+ " "+e.age);
}


}

最佳答案

HashSet使用哈希来比较对象。

您必须为equals类定义hashCodeEmployee

关于java - 如何删除HashSet中的重复项? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52647735/

10-13 04:25