java arraylist comparator,关于java:如何使用Comparator对ArrayList进行排序?
本問題已經(jīng)有最佳答案,請猛點這里訪問。
我有個班上的學(xué)生實現(xiàn)了一個靜態(tài)方法
public static Comparator getCompByName()
返回用于比較兩個學(xué)生對象的學(xué)生的新Comparator對象通過屬性"name"。
現(xiàn)在,我需要使用函數(shù)getCompabyName()按"name"對學(xué)生數(shù)組列表進行排序,以此來測試這一點。
這是我在學(xué)生班的比較器方法。
public static Comparator getCompByName()
{
Comparator comp = new Comparator(){
@Override
public int compare(Student s1, Student s2)
{
return s1.name.compareTo(s2.name);
}
};
return comp;
}
在我需要測試的地方
public static void main(String[] args)
{
// TODO code application logic here
//--------Student Class Test-------------------------------------------
ArrayList students = new ArrayList();
Student s1 = new Student("Mike");
Student s2 = new Student("Hector");
Student s3 = new Student("Reggie");
Student s4 = new Student("zark");
students.add(s1);
students.add(s2);
students.add(s3);
students.add(S4);
//Use getCompByName() from Student class to sort students
有人能告訴我如何使用我的主目錄中的getCompabyName()來按名稱對數(shù)組列表進行實際排序嗎?我對比較器不熟悉,對它們的用法也很難理解。這個方法返回一個比較器,所以我不確定如何實現(xiàn)它。我知道我需要使用getCompabyName()進行排序,我只是不確定如何實現(xiàn)它。
首先,選擇你最喜歡的排序算法。
@Sotiriosdelimanolis我需要使用getcompbyname()來排序,而不是另一種算法
Collections.sort(students, getCompByName())
我想你誤解了江戶一〔1〕的做法。它本身只是比較兩個元素。您必須實際編寫(或使用JDK中的)排序算法,。
@用戶3345200您可能想看看關(guān)于對象排序的官方教程。它簡潔、寫得很好,并且很好地解釋了如何實現(xiàn)和使用Comparator對對象進行排序。
使用collections.sort(list,comparator)方法:
Collections.sort(students, Student.getCompByName());
另外,在代碼中,在聲明List時,最好使用List接口:
List students = new ArrayList();
您還可以使用Student[]并將其傳遞給ArrayList構(gòu)造函數(shù)來加強代碼:
public static void main(String[] args) {
Student[] studentArr = new Student[]{new Student("Mike"),new Student("Hector"), new Student("Reggie"),new Student("zark")};
List students = new ArrayList(Arrays.asList(studentArr));
Collections.sort(students, Student.getCompByName());
for(Student student:students){
System.out.println(student.getName());
}
}
以下是完整來源的要點。
那是什么意思?
@Cosdicudatu Thanks,updated.
使用Collections.sort():
Collections.sort(students, getCompByName());
注意:可能有助于使比較器成為private static final變量。
注2:就地修改列表;不創(chuàng)建新列表。
總結(jié)
以上是生活随笔為你收集整理的java arraylist comparator,关于java:如何使用Comparator对ArrayList进行排序?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何解决ipad1升级没有响应的问题
- 下一篇: 计算机桌面图标怎么改,小编教你电脑如何更