首先 写出 一个person类 让他继承Comparable 构造函数和get/set不用说

 我们要覆盖父类中的comparto方法 代码如下 省略get/set

package a;

public class Person implements Comparable<Person> {
private int age;
private String name;

public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int compareTo(Person o) {
return this.getAge()-o.getAge();
}

public void show(){
System.out.println("姓名 " +name +" 年龄 "+age);
}

}

测试代码如下 不用解释...

package a;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestComparable {
public static void main(String args[]) {

List<Person> listCat1 = new ArrayList<Person>();
listCat1.add(new Person(35, "hlf"));
listCat1.add(new Person(36, "ddd"));
listCat1.add(new Person(38, "xxx"));

System.out.println("调用Collections.sort(List<T> list)listCat2升序排序:");
Collections.sort(listCat1);
for (int i = 0; i < listCat1.size(); i++) {
listCat1.get(i).show();
}

System.out.println("降序排列元素:");
Collections.sort(listCat1, Collections.reverseOrder());
for (int i = 0; i < listCat1.size(); i++) {
listCat1.get(i).show();
}
System.out.println("Collections.reverse 从列表中最后一个元素开始输出:");
Collections.reverse(listCat1);
for (int i = 0; i < listCat1.size(); i++) {
listCat1.get(i).show();
}
}
}

测试结果

调用Collections.sort(List<T> list)listCat2升序排序:
姓名    hlf 年龄 35
姓名    ddd 年龄 36
姓名    xxx 年龄 38
降序排列元素:
姓名    xxx 年龄 38
姓名    ddd 年龄 36
姓名    hlf 年龄 35
Collections.reverse 从列表中最后一个元素开始输出:
姓名    hlf 年龄 35
姓名    ddd 年龄 36
姓名    xxx 年龄 38

这个咱们是以 int类型来排序 如果是想按照string来排序 很简单 person类中的 compareto改成如下就ok

public int compareTo(Person o) {
return this.getName().compareTo(o.getName());
}


参考资料

java 集合排序