对于一个实现了Comparable接口的对象,该接口只能实现一次。如果在一个集合里面需要使用id排序,而在另外一个集合里需要按名字排序这时就需要在这个集合里面指定比较器。
Comparable接口声明了compareTo(Object o)方法
Comparator 接口声明了compare(Object o1,Object o2)方法
eg:
第一个树集是按照对象默认的id排序,第二个树集由指定的构造器按照name 排序
public class Employee implements Comparable{
private int id;
private String name;
public Employee(int id, String name){
this.id = id;
this.name = name;
}
public boolean equals(Object o){
if (o == null ){
return false;
}
if (this == o){
return true;
}
if(!(o instanceof Employee)){
return false;
}
Employee employee = (Employee)o;
return (this.id == employee.id) && (this.name.equals(employee.name));
}
public int hashCode(){
int result = 17;
result = 37 * result + id;
result = 37 * result + name.hashCode();
return result;
}
public String toString(){
return "id:"+id+",name:"+name+"";
}
public int compareTo(Employee employee){
//升序
return this.id - employee.id;
//降序
//return employee.id - this.id;
}
public String getName() {
return name;
}
}
/*******************************************************************/
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Comparator;
public class TreeSetTest {
public static void main(String []args){
//使用的是实现了Compable 接口对象默认的排序方式,按id升序排序
SortedSet treeSet = new TreeSet&