JavaDoc的定義設定爲:Java的設置得到重複條目
不包含重複元素的集合。更正式地,設置 不含對E1和e2元素,使得e1.equals(E2)
要驗證相同的,我創建了一個非常簡單的程序:
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
這意味着new Employee(10).equals(new Employee(10))
返回true,而set.add(new Employee(10)); set.add(new Employee(10));
將對象添加兩次。
我的代碼有什麼問題?
閱讀:http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683 – Tom 2011-12-14 12:58:28