java对象数组排序的一种方式

JAVA中可以通过实现比较器Comparator<T>接口来对对象数组进行排序
emmmmm这东西貌似只能直接上代码。。。。

import java.util.Arrays;
import java.util.Comparator;

/**
 * Created by admin on 2017/12/19.
 */
class Person{
   public String name;
   public int age;
   Person(String name , int age){
       this.name = name;
       this.age = age;
   }
}
class PersonCmp implements Comparator<Person>{
    @Override
    //首先按照名字排序,然后按照年龄排序
    public int compare(Person o1, Person o2) {
        int x = 0;
        if(o1.name.equals(o2.name)){
            if(o1.age<o2.age){
                x = -1;
            }
            else x = 1;
        }
        else{
            x= o1.name.compareTo(o2.name);
        }
        return x;
    }
}
public class ObjectArraySort {
    public static void main(String[] args) {
        Person p[] = new Person[4];
        p[0] = new Person("D",10);
        p[1] = new Person("D",1);
        p[2] = new Person("A",10);
        p[3] = new Person("A",1);
        for(Person x : p){
            System.out.println(x.name+","+x.age);
        }
        /*
         *D,10
         *D,1
         *A,10
         *A,1
         */
        Arrays.sort(p,new PersonCmp());
        System.out.println("----");
        for(Person x : p){
            System.out.println(x.name + "," + x.age);
        }
        /*
         *A,1
         *A,10
         *D,1
         *D,10
         */
    }

}
View Code
原文地址:https://www.cnblogs.com/rtyfcvb/p/8064700.html