概述:本示例实现对象按年龄升序 人气升序排序功能 姓名升序 降序排序功能
package ch02;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author YaoShiyou 实现对象排序
*
*/
public class Person {
// 姓名
private String name;
// 年龄
private int age;
// 人气
private int hobby;
public Person(String name) {
this.name = name;
}
public Person(String name, int age) {
this(name);
this.age = age;
}
public Person(String name, int age, int hobby) {
this(name, age);
this.hobby = hobby;
}
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 getHobby() {
return hobby;
}
public void setHobby(int hobby) {
this.hobby = hobby;
}
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
list.add(new Person("g1", 18, 122));
list.add(new Person("g2", 17, 244));
list.add(new Person("g3", 45, 243));
list.add(new Person("g4", 9, 67));
list.add(new Person("g5", 98, 2));
System.out.println("排序前---");
for (Person person : list) {
System.out.println(person.getName() + "\t" + person.getAge() + "\t"
+ person.getHobby());
}
// Collections调用sort 方法 参数为
Collections.sort(list, new AgeComparatorAsc());
System.out.println("年龄排序后----");
for (Person person : list) {