1. 为集合中对象的所属类实现了 java.lang.Comparable 接口
对需要排序的person类实现Comparable接口,实现接口的CompareTo方法来定义排序的规则
public class Person implements Comparable{
private final int id;
private String name;
private int age;
public Person(int id,String name,int age){
this.id = id;
this.name = name;
this.age = age;
}
public int getId(){
return id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
@Override
public String toString(){
return "Id: " + id + "/tName: " + name + "/tAge: " + age;
}
@Override
public int compareTo(Object o){ // 实现 Comparable 接口的抽象方法,定义排序规则
Person p = (Person)o;
return this.id - p.id; // 升序排列,反之降序
}
@Override
public boolean equals(Object o){ //equals
boolean flag = false;
if(o instanceof Person){
if(this.id == ((Person)o).id)
flag = true;
}
return false;
}
}
测试类
import java.util.TreeSet;
import java.util.Iterator;
public class TestComparable{
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(new Person(1003," 张三 ",15));
ts.add(new Person(1008," 李四 ",25));
ts.add(new Person(1015," 王五 ",73));
ts.add(new Person(1001," 赵六 ",49));
Iterator it = ts.iterator();
while(it.hasNext()){
Person employee = (Person)it.next();
System.out.println(employee);
}
}
}
2. 为集合指定比较器 java.lang.Comparator 的实现类
需要排序的类
//需要排序的类的对象
public class Person{
private final int id;
private String name;
private int age;
public Person(int id,String name,int age){
this.id = id;
this.name = name;
this.age = age;
}
public int getId(){
return id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
@Override
public String toString(){
return "Id: " + id + "/tName: " + name + "/tAge: " + age;
}
}
//创建person类的比较器
package ClassTest;
import java.util.Comparator;
public class PersonComparetor implements Comparator{
public int compare(Person o1, Person o2) {
// return o1.getId()-o2.getId(); //升序
return o2.getId()-o1.getId(); //降序
}
}
//测试类
public class TestComparable {
public static void main(String[] args) {
List ts=new ArrayList();
ts.add(new Person(1003," 张三 ",15));
ts.add(new Person(1008," 李四 ",25));
ts.add(new Person(1015," 王五 ",73));
ts.add(new Person(1001," 赵六 ",49));
PersonComparetor pc=new PersonComparetor();
Collections.sort(ts, pc);
for(Person p:ts){
System.out.println(p);
}
}
}
分享到:
2014-09-23 15:21
浏览 1174
评论