我有一个类名为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()进行排序,只是不确定如何实现。
Collections.sort(students, getCompByName())
- Gábor BakosComparator
的作用。它本身只是比较两个元素。你必须实际编写(或使用JDK中的算法)排序算法。 - Sotirios DelimanolisComparator
来对对象进行排序。 - Jason C