I was trying a small code using Comparator to sort list of student through there roll number. But I am getting compile time error at this line:
Collections.sort(l);
Below my test code:
package test;
import java.util*;
public class StudentUsingComparator implements
Comparator<StudentUsingComparator> {
int roll;
String name;
public StudentUsingComparator(int roll, String name) {
this.name = name;
this.roll = roll;
}
@Override
public int compare(StudentUsingComparator s1, StudentUsingComparator s2) {
return s1.roll - s2.roll;
}
public static void main(String[] args) {
StudentUsingComparator student1 = new StudentUsingComparator(10, "ab");
StudentUsingComparator student2 = new StudentUsingComparator(30, "cd");
StudentUsingComparator student3 = new StudentUsingComparator(20, "bc");
List<StudentUsingComparator> l = new ArrayList<StudentUsingComparator>();
l.add(student1);
l.add(student2);
l.add(student3);
System.out.println("unsorted collection is: " + l);
Collections.sort(l); //m getting error in this line
System.out.println("sorted collection is: " + l);
}
}
Error message says:
bound mismatch: the generic method sort(List) of type collection is not applicable for the arguments list(). the inferred type StudentUsingComparator is not a valid substitute for the bounded parameter>