繁体   English   中英

ArrayList按长度排序

[英]ArrayList sort by length

我想按矢量对象的长度对对象的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));

我希望FacultateLists2,s3,s一样排序。

Collections.sort与自定义比较器一起使用:

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

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

(顺便说一句,以后FacultateList混淆,Java的约定是变量以小写字母开头,所以facultateList而不是FacultateList 。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM