Java重写compare,完成List排序

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
 public static void main(String args[]) {
  /*
   * 造一个LIST
   */
  List<Persion> perList = new ArrayList<Persion>();
  /*
   * 造假数据,数据从小到大排列
   */
  for (int i = 0; i < 20; i++) {
   Persion persion = new Persion();
   persion.name = "xiaoming";
   persion.age = i;
   perList.add(persion);
  }
  /*
   * 打印数据
   */
  System.out.println("----排序前的数据----");
  for (int i = 0; i < perList.size(); i++) {
   Persion persion = perList.get(i);
   System.out.println("persion.name: " + persion.name
     + " persion.age: " + persion.age);
  }
  /*
   * 排序
   */
  Collections.sort(perList, new Comparator<Persion>() {
   @Override
   public int compare(Persion o1, Persion o2) {
    return o2.age - o1.age;
   }
  });
  /*
   * 打印数据
   */
  System.out.println("----排序后的数据----");
  for (int i = 0; i < perList.size(); i++) {
   Persion persion = perList.get(i);
   System.out.println("persion.name: " + persion.name
     + " persion.age: " + persion.age);
  }
 }
 public static class Persion {
  public String name;
  public int age;
 }
}

你可能感兴趣的:(Java)