我有一个实现静态方法的班级学生
public static Comparator<Student> getCompByName()
为 Student 返回一个新的比较器对象,该对象比较 2 个 Students 对象
通过属性“名称”。
我现在需要使用我的函数 getCompByName() 按“名称”对学生 ArrayList 进行排序来测试这一点。
这是我的 Student 类中的比较器方法。
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() 进行排序,我只是不确定如何实现它。
Use the Collections.sort(列表,比较器) http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29 method:
Collections.sort(students, Student.getCompByName());
另外,在您的代码中最好使用List
声明时的接口List
:
List<Student> students = new ArrayList();
您还可以通过使用来收紧代码Student[]
并将其传递给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());
}
}
这里有一个完整源码的要点 https://gist.github.com/kmb385/9477347.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)