Use the Collections.sort(List, Comparator) method:
Collections.sort(students, Student.getCompByName());
Also in your code it would be good to use the List
interface when declaring the List
:
List<Student> students = new ArrayList();
You could also tighten up the code by using a Student[]
and passing it to the ArrayList
constructor:
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());
}
}
Here is a Gist of the full source.