如何使用比较器对 ArrayList 进行排序? [英] How to sort ArrayList using Comparator?

查看:35
本文介绍了如何使用比较器对 ArrayList 进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现静态方法的学生类

I have a Class Student that Implements a static method

public static Comparator<Student> getCompByName()

为 Student 返回一个新的比较器对象,该对象比较 2 个 Students 对象通过属性名称".

that returns a new comparator object for Student that compares 2 Students objects by the attribute 'name'.

我现在需要通过使用我的函数 getCompByName() 按姓名"对学生 ArrayList 进行排序来测试这一点.

I need to now test this by sorting a students ArrayList by 'name' using my function getCompByName().

这是我在 Student 类中的 Comparator 方法.

Here is my Comparator method in my Student class.

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() 进行排序,我只是不确定如何实现它.

Can anyone show me how I would use the getCompByName() in my main to actually sort the ArrayList by name? Im new to comparators and having a hard time with their usages. The method returns a comparator, so Im not sure how this will be implemented. I know I need to use getCompByName() to sort, im just not sure how to implement it.

推荐答案

使用 Collections.sort(List, Comparator) 方法:

Collections.sort(students, Student.getCompByName());

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

Also in your code it would be good to use the List interface when declaring the List:

List<Student> students = new ArrayList();

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

You could also tighten up the code by using a Student[] and passing it to the ArrayList constructor:

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());
    }
}

这是一个完整源代码的要点.

这篇关于如何使用比较器对 ArrayList 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆