简体   繁体   English

ArrayList按长度排序

[英]ArrayList sort by length

I want to sort an ArrayList of objects by the length of the vector objects. 我想按矢量对象的长度对对象的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));

I want FacultateList to be ordered like s2,s3,s . 我希望FacultateLists2,s3,s一样排序。

Use Collections.sort with a custom comparator: Collections.sort与自定义比较器一起使用:

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

Alternatively, if this is the default way to sort students, make Student implement Comparable<Student> , implement the appropriate compareTo method in the class itself, and use Collections.sort without the custom comparator. 或者,如果这是对学生进行排序的默认方式,则使Student实现Comparable<Student> ,在类本身中实现适当的compareTo方法,并使用不带自定义比较器的Collections.sort

(Just an aside that will save you confusion later, the convention in Java is that variables start with a lowercase letter, so facultateList , not FacultateList .) (顺便说一句,以后FacultateList混淆,Java的约定是变量以小写字母开头,所以facultateList而不是FacultateList 。)

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

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