我的工作與TreeSet
收集用下面的代碼:是什麼平等之間的差異,包含的方法
import java.util.*;
public class Employee implements Comparable<Employee>{
private int ID;
public Employee(int iD) {
ID = iD;
}
@Override
public int compareTo(Employee obj) {
return this.ID-obj.ID;
}
private static void intoTreeSet() {
Employee e1=new Employee(4);
Employee e2=new Employee(2);
Employee e3=new Employee(1);
Employee e4=new Employee(5);
Employee e5=new Employee(3);
Employee eTemp=new Employee(3);
Set<Employee> set=new TreeSet();
set.add(e1);set.add(e2);set.add(e3);set.add(e4);set.add(e5);
System.out.println("output says: ");
for(Employee e:set){
System.out.print(e.ID+" ~ ");
}
System.out.println();
if(set.contains(eTemp)){
System.out.println("C O N T A I N S !!!");
}
if(e5.equals(eTemp)){
System.out.println("E Q U A L S !!!");
}
}
public static void main(String[] args) {
intoTreeSet();
}
}
輸出
output says:
1 ~ 2 ~ 3 ~ 4 ~ 5 ~
C O N T A I N S !!!
我很困惑,看看輸出。我想知道,如果它不通過equals
的情況下,那麼它怎麼通過contains
的情況。
我知道兩個對象只有在它們的類覆蓋equals
方法時纔可以相等,並且它們根據某些屬性是相等的。我故意沒有覆蓋equals
的方法,看看如何contains
工作。如果它是基於非樹的收集可以說一個ArrayList
它不會通過contains
測試。爲什麼這樣?任何人都可以解釋這種行爲並清除我的困惑。
「一個TreeSet實例使用其compareTo(或compare)方法執行所有元素比較,因此從該方法看,被這個方法視爲相等的兩個元素相等。」 –
來自幾年前的類似問題:http://stackoverflow.com/questions/12761532/equals-and-comparable-with-sets – FoggyDay
http://stackoverflow.com/questions/6476600/ –