Java 如何使用Comparator对ArrayList进行排序?
我有一个学生,他实现了一个静态方法Java 如何使用Comparator对ArrayList进行排序?,java,sorting,collections,arraylist,comparator,Java,Sorting,Collections,Arraylist,Comparator,我有一个学生,他实现了一个静态方法 public static Comparator<Student> getCompByName() 公共静态比较器getCompByName() 为比较2个Student对象的Student返回一个新的comparator对象 通过属性“name” 我现在需要通过使用函数getCompByName()按“名称”对students ArrayList排序来测试这一点 这是我学生课堂上的比较器方法 public static Comparator&
public static Comparator<Student> getCompByName()
公共静态比较器getCompByName()
为比较2个Student对象的Student返回一个新的comparator对象
通过属性“name”
我现在需要通过使用函数getCompByName()按“名称”对students ArrayList排序来测试这一点
这是我学生课堂上的比较器方法
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;
}
公共静态比较器getCompByName()
{
比较器comp=新比较器(){
@凌驾
公共整数比较(学生s1、学生s2)
{
返回s1.name.compareTo(s2.name);
}
};
返回补偿;
}
还有我需要测试的地方
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
publicstaticvoidmain(字符串[]args)
{
//此处的TODO代码应用程序逻辑
//--------学生班级考试-------------------------------------------
ArrayList students=新ArrayList();
学生s1=新学生(“迈克”);
学生s2=新生(“赫克托”);
学生s3=新生(“Reggie”);
学生s4=新生(“zark”);
学生。加上(s1);
学生。添加(s2);
学生。添加(s3);
学生。加上(S4);
//使用学生类中的getCompByName()对学生进行排序
有人能告诉我如何在main中使用getCompByName()来按名称对ArrayList进行实际排序吗?我对comparators不太熟悉,对它们的用法很难理解。该方法返回一个comparator,所以我不确定这将如何实现。我知道我需要使用getCompByName()要排序,我只是不知道如何实现它。使用:
注意:使比较器成为私有静态final
变量可能很有用
注2:就地修改列表;不创建新列表。使用以下方法:
在您的代码中,最好在声明列表
时使用列表
界面:
List<Student> students = new ArrayList();
这是一个。首先,选择您最喜欢的排序算法。@SotiriosDelimanolis我需要使用getCompByName()进行排序,而不是使用另一个算法
Collections.sort(学生,getCompByName())
我想您误解了比较器的功能。它本身只是比较两个元素。您必须实际编写(或使用JDK中的排序算法。@user3345200您可能想看一看关于的官方教程。该教程简明且编写良好,很好地解释了如何实现和使用比较器
对对象进行排序。这就是集合。排序(*List*,Comparator)
@CostiCiudatu谢谢,已更新。
Collections.sort(students, Student.getCompByName());
List<Student> students = new 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());
}
}