如何删除HashSet中的重复项?

时间:2018-10-04 13:16:52

标签: java hashset

在下面的代码中,我在哈希集中添加了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 个答案:

答案 0 :(得分:4)

HashSet使用哈希值比较对象。

您必须为equals类定义hashCodeEmployee

答案 1 :(得分:1)

您需要在hashcode()类中实现equals()Employee方法。

答案 2 :(得分:0)

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

为Employee创建一个equals方法。

答案 3 :(得分:0)

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

如果您不希望集合中有重复项,则应考虑为什么要使用允许重复项的集合。删除重复元素的最简单方法是将内容添加到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 - the answer here