我的工作与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/ –