ArrayList按长度排序

stu*_*ent 1 java

我想ArrayList按矢量对象的长度对对象进行排序.

double[] s ={1,2,3,4};
double[] s2 ={1,2};
double[] s3 ={1,2,3};

Student[] Facultate ={new Student(s),new Student(s2)};
ArrayList<Student> FacultateList = new ArrayList<Student>(Arrays.asList(Facultate));
Run Code Online (Sandbox Code Playgroud)

我想要FacultateList订购s2,s3,s.

mk.*_*mk. 5

使用Collections.sort带有自定义比较:

Collections.sort(facultateList, new Comparator<Student>() {
    public int compare(Student a, Student b) {
        return a.getLength().compareTo(b.getLength());
    }
});
Run Code Online (Sandbox Code Playgroud)

或者,如果这是对学生进行排序的默认方式,那么make Student实现Comparable<Student>,compareTo在类本身中实现适当的方法,并在Collections.sort没有自定义比较器的情况下使用.

(稍后一点就可以省去你的困惑,Java中的约定是变量以小写字母开头,所以facultateList,不是FacultateList.)