【发布时间】:2014-04-14 08:57:34
【问题描述】:
我有一个实现静态方法的班级学生
public static Comparator<Student> getCompByName()
为学生返回一个新的比较器对象,比较 2 个学生对象 通过属性“名称”。
我现在需要通过使用我的函数 getCompByName() 按“姓名”对学生 ArrayList 进行排序来测试这一点。
这是我的 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
谁能告诉我如何在我的 main 中使用 getCompByName() 来实际按名称对 ArrayList 进行排序?我是比较器的新手,并且很难使用它们。该方法返回一个比较器,所以我不确定这将如何实现。我知道我需要使用 getCompByName() 来排序,我只是不确定如何实现它。
【问题讨论】:
-
首先,选择你喜欢的排序算法。
-
@SotiriosDelimanolis 我需要使用 getCompByName() 进行排序,而不是其他算法
-
Collections.sort(students, getCompByName()) -
我想你误解了
Comparator的作用。它本身只是比较两个元素。您必须实际编写(或使用 JDK 中的)排序算法。 -
@user3345200 你可能想看看Object Ordering上的官方教程。它简洁且写得很好,很好地解释了如何实现和使用
Comparator对对象进行排序。
标签: java sorting collections arraylist comparator