- 写一个Person类,继承自Comparable接口,只需重写compareTo():
package ComparableTest;
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
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 int compareTo(Person o) {
return name.compareTo(o.name);
}
}
- 写一个Main类,实现main函数:
package ComparableTest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import ComparableTest.Main.AgeAscComparator;
public class Main {
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<Person>();
list.add(new Person("c", 20));
list.add(new Person("A", 30));
list.add(new Person("b", 10));
list.add(new Person("a", 40));
print(list,"原始排序:");
//1. 利用Comparable实现name排序
Collections.sort(list);
print(list,"利用Comparable实现name排序后:");
//2. 利用Comparator实现age升序
Collections.sort(list, new AgeAscComparator());
print(list,"利用Comparator按age升序排序后:");
//3. 利用Comparator实现age降序
Collections.sort(list, new AgeDecComparator());
print(list,"利用Comparator按age降序排序后:");
}
//利用Comparator按age升序排序
public static class AgeAscComparator implements Comparator {
@Override
public int compare(Object arg0, Object arg1) {
Person p0=(Person) arg0;
Person p1=(Person) arg1;
return p0.getAge()-p1.getAge();
}
}
//利用Comparator按age降序排序
public static class AgeDecComparator implements Comparator {
@Override
public int compare(Object arg0, Object arg1) {
Person p0=(Person) arg0;
Person p1=(Person) arg1;
return p1.getAge()-p0.getAge();
}
}
public static void print(ArrayList<Person> list,String str){
System.out.println();
System.out.print(str);
for(Person p:list)
System.out.print(p.getName() ":" p.getAge() " ");
}
}
输出结果:
代码语言:javascript复制原始排序:c:20 A:30 b:10 a:40
利用Comparable实现name排序后:A:30 a:40 b:10 c:20
利用Comparator按age升序排序后:b:10 c:20 A:30 a:40
利用Comparator按age降序排序后:a:40 A:30 c:20 b:10
如果想实现按name降序排序,只需将Person类中的compareTo中的return改为:
代码语言:javascript复制@Override
public int compareTo(Person o) {
return o.name.compareTo(name);
}
输出:
利用Comparable实现name降序排序后:c:20 b:10 a:40 A:30
总结: 升序:return name.compareTo(o.name); 降序:return o.name.compareTo(name);