1

在下面的代码中,我在哈希集中添加了 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);
}


}
4

4 回答 4

4

HashSet 使用哈希来比较对象。

你必须为你的班级定义equals和。hashCodeEmployee

于 2018-10-04T13:20:17.013 回答
1

你需要在你的类中实现hashcode()andequals()方法。Employee

于 2018-10-04T13:21:40.247 回答
1

只要这没有被重复,正确的答案是:

如果您不想在集合中重复,您应该考虑为什么要使用允许重复的集合。删除重复元素的最简单方法是将内容添加到 Set(不允许重复),然后将 Set 添加回 ArrayList:

List<String> al = new ArrayList<>();
// add elements to al, including duplicates
Set<String> hs = new HashSet<>();
hs.addAll(al);
al.clear();
al.addAll(hs);

当然,这会破坏 ArrayList 中元素的顺序。

如果您希望保留订单,另请参阅 LinkedHashSet。

致谢:jonathan-stafford - 答案在这里

于 2018-10-04T13:24:33.763 回答
0

您的 equals 方法需要设置。哈希集不应允许存在两个“相等”的对象。

为 Employee 创建一个 equals 方法。

于 2018-10-04T13:20:11.903 回答