[英]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));
我希望FacultateList
像s2,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.