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.
It may not be so obvious based on error message, but if you take a look at documentation of Collection.sort
you fill find that this method (like rest of standard API methods) expects list of instances implementing already defined in API interface which in this case is java.lang.Comparable
.
So don't try to create your own Comparable
interface. Remember that if some method expects some type, this type must be already defined somewhere (otherwise class with such method wouldn't compile because method can't use some unknown/undefined type).
Also comparing method defined in java.util.Comparable
is compareTo
not CompareTo
(Java is case sensitive so these methods are not treated as equal).
Other problems are
Student
doesn't have temp
field so
} else if (this.age < otherStudent.temp) {
should probably be
} else if (this.age < otherStudent.age) {
or even better, instead of this age
comparing conditions if(..<..){-1} else if(..==..){0} else {1}
simply use
return Integer.compare(age, otherStudent.age);
in constructor you need this.name
to determine which name
you are refering to. this.name
means field of this instance, name
is reference to variable passed to constructor. So you need
public Student(String name, int age) {
this.name = name;
this.age = age;
}