如果不按照对象中具备的自然顺序进行排序,或者说对象不具备自然顺序,可以使用TreeSet集合第二种排序方式,让集合自身具备比较功能。这就是通过定义一个类实现Comparator接口,覆盖它的compare方法,将该类对象作为参数传递给TreeSet集合的构造函数。
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
class Person extends Object implements Comparable{ //先继承后实现
String name;
int age;
public Person(){
super();
}
public Person(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;
}
public int compareTo(Object o){ //以Person对象的年龄进行从小到大的排序
Person p=(Person)o;
/* 此部分代码可被下两句代码替换
if(this.age>p.age) return 1; //返回正数
if(this.age<p.age) return -1; //返回负数
if(this.age==p.age){ //当主要条件相等时按次要条件排序
return this.name.compareTo(p.name); //String类中的compareTo方法
} */
int temp=this.age-p.age; //先按年龄排,再按姓名排
return temp==0?this.name.compareTo(p.name):temp;
/* 先按姓名排,再按年龄排
int temp=this.name.compareTo(p.name);
return temp==0?this.age-p.age:temp;
*/
}
}
//创建一个根据Person类的name进行排序的比较器
class ComparatorByName implements Comparator{ //按姓名比较,继承Comparator接口
public int compare(Object o1,Object o2){ //覆盖compare方法
Person p1=(Person)o1;
Person p2=(Person)o2;
int temp=p1.getName().compareTo(p2.getName());
return temp==0?p1.getAge()-p2.getAge():temp;
}
}
public class TreeSetDemo{
public static void main(String[] args){
TreeSet ts=new TreeSet(new ComparatorByName()); //通过构造函数传递参数
ts.add(new Person("zhangsan",28));
ts.add(new Person("wangwu",29));
ts.add(new Person("lisi",21));
ts.add(new Person("zhouqi",29));
ts.add(new Person("zhaoliu",25));
ts.add(new Person("zhaoliu",30));
ts.add(new Person("zhaoliu",21));
Iterator it=ts.iterator();
while(it.hasNext()){
Person p = (Person)it.next();
System.out.println(p.getName()+":"+p.getAge());
}
}
}
运行结果: