I'm wondering why i'm getting an error after trying to sort the List. The error happens when i try to sort the list containing "Student" objects.
import java.lang.reflect.Array;
import java.util.*;
import java.util.ArrayList;
public class mainProgram {
public static void main(String[] args) {
List<Student> classStudents = new ArrayList<Student>();
//Add 4 students to List
classStudents.add(new Student("Charles", 22));
classStudents.add(new Student("Chris", 25));
classStudents.add(new Student("Robert", 23));
classStudents.add(new Student("Adam", 21));
//sort and print
Collections.sort(classStudents); //Why does this not work?
System.out.println("classStudent(Sorted) ---> "
+ Arrays.toString(classStudents.toArray()));
}
}
class Student implements Comparable<Student>{
// fields
private String name;
private int age;
//Constructor
public Student(String name, int age){
name = name;
age = age;
}
//Override compare
public int CompareTo(Student otherStudent){
if(this.age == otherStudent.age){
return 0;
} else if(this.age < otherStudent.temp){
return -1;
} else{
return 1;
}
}
//Override toString
public String toString(){
return this.name + " " + this.age;
}
}
interface Comparable<Student>{
int CompareTo(Student otherStudent);
String toString();
}
The Error is:
Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<Student>). The inferred type Student is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>
I do not understand what the error means and how to fix it. Your input will be very much appreciated.