package java1.basic;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetTest {
public static void main(String args[]){
TreeSet<M> t=new TreeSet<M>(new Comparator<M>(){
public int compare(M obj1,M obj2){
System.out.println(obj1+":"+obj2);
//输出语句的结果为obj1为要加入的对象,而obj2为已经加入集合中的对象。
if(obj1.getAge()>obj2.getAge())
return 1;//这儿就可以理解为大的排在后面
if(obj1.getAge()<obj2.getAge())
return -1;//小的排在前面
return 0;
}
});//我的是匿名内部类
t.add(new M("zhangsan",16));
t.add(new M("lisi",17));
t.add(new M("lii",18));
}
}
class M{
private String name ;
private int age;
public M(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.name+"::"+this.age;
}
}
//
//如果Comparator与Comparable同在,那么在排序时使用的就是Comparator中的compare
|