如何使用Comparator对ArrayList进行排序?

13

我有一个类名为Student的类,它实现了一个静态方法

public static Comparator<Student> getCompByName()

该函数返回一个新的比较器对象,用于比较2个具有“name”属性的Student对象。

现在我需要通过使用我的getCompByName()函数对学生ArrayList按照“name”排序来进行测试。

这是我的Student类中的Comparator方法。

public static Comparator<Student> getCompByName()
{   
 Comparator comp = new Comparator<Student>(){
     @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<Student> 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

有人可以向我展示如何在主函数中使用getCompByName()来按名称对ArrayList进行排序吗?我很新到比较器,并且在它们的用法方面遇到了困难。该方法返回一个比较器,因此我不确定如何实现它。我知道我需要使用getCompByName()进行排序,只是不确定如何实现。


首先,选择你喜欢的排序算法。 - Sotirios Delimanolis
@SotiriosDelimanolis 我需要使用getCompByName()来排序,而不是其他算法。 - Reeggiie
Collections.sort(students, getCompByName()) - Gábor Bakos
1
我认为你误解了Comparator的作用。它本身只是比较两个元素。你必须实际编写(或使用JDK中的算法)排序算法。 - Sotirios Delimanolis
@user3345200 你可能想要查看官方教程关于对象排序的部分。该教程简明扼要,文笔流畅,并且很好地解释了如何实现和使用Comparator来对对象进行排序。 - Jason C
2个回答

16
使用 Collections.sort(List, Comparator) 方法:
Collections.sort(students, Student.getCompByName());

在你的代码中,声明 List 时最好使用 List 接口:

List<Student> students = new ArrayList();

您还可以通过使用 Student[] 并将其传递给 ArrayList 构造函数来压缩代码:

public static void main(String[] args) {
    Student[] studentArr = new Student[]{new Student("Mike"),new Student("Hector"), new Student("Reggie"),new Student("zark")};
    List<Student> students = new ArrayList<Student>(Arrays.asList(studentArr));
    Collections.sort(students, Student.getCompByName());

    for(Student student:students){
        System.out.println(student.getName());
    }
}

这里是完整源代码的Gist链接


1
这是 Collections.sort(*List*, Comparator) - Costi Ciudatu
@CostiCiudatu 谢谢,已更新。 - Kevin Bowersox

5

使用 Collections.sort() 方法:

Collections.sort(students, getCompByName());

注意:将您的比较器作为private static final变量可能会很有用。
注意2:直接修改列表;不创建新列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接