簡體   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