如何使用Object参数对Arraylist中的对象进行排序

Keb*_*mer 1 java sorting arraylist object

我在排序Arraylist中的对象时遇到问题,因为我是排序对象的新手.

对arraylist进行排序是非常基本的,但是对对象的arraylist进行排序是完全不同的事情.基本上我已经在堆栈溢出中搜索代码,人们似乎使用比较器来解决他们的问题,但他们没有解释如何实际调用该方法并将其投入使用,这就是我在这里的原因.

使用下面的代码,我试图用参数 - 字符串名称,int年龄和字符串课程对学生的arraylist进行排序.然后我有另一个类来存储Student对象并在类中对它们进行排序.这是我有的:

Student.java

public class Student {

    private String name, course;
    private int age;

    public Student(String name, int age, String course) {
        this.name = name;
        this.age = age;
        this.course = course;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getCourse() {
        return course;
    }
}
Run Code Online (Sandbox Code Playgroud)

CompareObj.java

import java.util.*;

public class CompareObj implements Comparator<Student>{

    private ArrayList<Student> sList;

    public CompareObj() {
        sList = new ArrayList<Student>();
    }

    @Override
    public int compare(Student s1, Student s2) {
         return s2.getName().compareTo(s1.getName());
    }

    public void add(Student s1) {
        sList.add(s1);
    }

    public void displayList() {
        for(int i = 0; i<sList.size();i++) {
            System.out.println(sList.get(i).getName());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在CompareObj类中,如何使用已实现的方法比较(s1,s2),如何使用此方法对学生对象的arraylist进行排序?

Wun*_*orn 8

how can i use this method to sort my arraylist of student objects?
Run Code Online (Sandbox Code Playgroud)

你不需要打电话给compare()自己.您可以Collections.sort()通过调用compare()方法将比较器传递给您进行排序.


通过使用自定义类CompareObj,

Collections.sort(studentList, new CompareObj());
Run Code Online (Sandbox Code Playgroud)

或者没有的另一种方式CompareObj是,

Collections.sort(studentList,new Comparator<Student>() {
         @Override
        public int compare(Student s1, Student s2) {
                return s1.getName().compareToIgnoreCase(s2.getName());
        }
    });
Run Code Online (Sandbox Code Playgroud)