I am trying out Java Collections.sort method and get an error (please see in the code) which I don't understand. Java says, "The method sort(List, Comparator) in the type Collections is not applicable for the arguments (List, StudentComparator)". I don't know what I am doing wrong here.
I have a class called Students and it looks like this.
//import all necessary
public class Students implements Comparable<Students>{
public List<String> list;
public String firstname;
public String lastname;
public Students(){
list = new ArrayList<String>();
}
public void addStudent(String firstname, String lastname){
this.firstname = firstname;
this.lastname = lastname;
list.add(firstname + " " + lastname);
Collections.sort(list); //This is fine though.
Collections.sort(list, new StudentComparator()); //This gives me the error. I want to use this for custom comparison and in this case, by student's last name.
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
@Override
public int compareTo(Students student) {
return this.compareTo(student);
}
}
And I have another class that implements Comparator.
public class StudentComparator implements Comparator<Students>{
@Override
public int compare(Students student1, Students student2) {
return student1.getLastname().compareTo(student2.getLastname());
}
}
I have no problem with using Anonymous Comparator interface and implement it right in the Students class, but when I create a new class that implements Comparator interface and try to sort the list, it gives me the error.
Collections.sort(list, (Comparator<Students>) (new StudentComparator()));List<String>with aComparator<Students>.