本文介绍了Java集获取重复条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
JavaDoc将集合定义为:
JavaDoc defines set as :
同样,我创建了一个非常简单的程序:
To verify the same, i created a very simple program:
import java.util.HashSet;
public class CheckHashSet {
public static void main(String[] args) {
HashSet<Employee> set = new HashSet<Employee>();
set.add(new Employee(10));
set.add(new Employee(10));
System.out.println(set.size());
System.out.println(new Employee(10).equals(new Employee(10)));
}
private static class Employee implements Comparable<Employee> {
private final int id;
public Employee(int id) {
this.id = id;
}
@Override
public int compareTo(Employee o) {
return this.id - o.id;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Employee) {
return compareTo((Employee)obj)==0;
}
return false;
}
}
}
程序的输出为
2
true
这意味着新员工(10).equals(新员工(10))
返回true,而 set.add (新员工(10)); set.add(new Employee(10));
将对象添加两次。
This means new Employee(10).equals(new Employee(10))
returns true whereas set.add(new Employee(10)); set.add(new Employee(10));
adds the object twice.
我的代码有什么问题?
推荐答案
您的 Employee
类不会覆盖 hashCode
-它需要这样做才能使任何基于哈希的集合正常工作。
Your Employee
class doesn't override hashCode
- it needs to do so in order for any hash-based collection to work.
例如:
@Override
public int hashCode() {
return id;
}
这篇关于Java集获取重复条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!