I have a Class Student that Implements a static method
public static Comparator<Student> getCompByName()
that returns a new comparator object for Student that compares 2 Students objects by the attribute 'name'.
I need to now test this by sorting a students ArrayList by 'name' using my function getCompByName().
Here is my Comparator method in my Student class.
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;
}
And Main where I need to test
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
Can anyone show me how I would use the getCompByName() in my main to actually sort the ArrayList by name? Im new to comparators and having a hard time with their usages. The method returns a comparator, so Im not sure how this will be implemented. I know I need to use getCompByName() to sort, im just not sure how to implement it.
Collections.sort(students, getCompByName())Comparatordoes. On its own it just compares two elements. You have to actually write (or use the ones in the JDK) the sorting algorith,.Comparatorto sort objects.