【问题标题】:How to remove duplicates in HashSet? [duplicate]如何去除 HashSet 中的重复项? [复制]
【发布时间】:2018-10-04 13:16:52
【问题描述】:

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


}

【问题讨论】:

标签: java hashset


【解决方案1】:

HashSet 使用哈希来比较对象。

您必须为您的Employee 类定义equalshashCode

【讨论】:

    【解决方案2】:

    只要不重复,正确答案是:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        为 Employee 创建一个 equals 方法。

        【讨论】:

        • 还有hashCode方法需要被覆盖
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-23
        • 1970-01-01
        • 2015-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多