Java ArrayList动态数组排序

使用Collections.sort(ArrayList list)方法。 ArrayList中的类型必须实现Comparable接口,重写compareTo方法,根据需要返回对比结果。如:

class People implements Comparable {
    //必须实现Comparable接口
    String name;
    int age;

    People(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Object o) {
        //重写Comparable接口的compareTo方法 
        //先根据age排序,如果age相同,再根据name排序
        People p = (People) o;
        int result;
        if (age > p.age) {
            result = 1;
        } else if (age == p.age) {
            result=0;
        } else {
            result = -1;
        }
        if(result==0){
            result=name.compareTo(p.name);
        }
        return result;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "Name:"+name+" Age:"+age;
    }

}