I came up with a small problem while doing my homework.
I have a Person class
public class Person {
protected String code;
protected String name;
}
And a subclass called Student
public class Student extends Person implements Comparable<Student>{
private double grade;
@Override
public int compareTo(Student that){
return Double.compare(grade, that.grade);
}
}
The teacher wanted us to create a Professor class to manage Student using ArrayList
public class Professor {
private List<Person> arr;
public Professor() {
arr = new ArrayList();
}
}
After adding about ten students to the ArrayList and we're asked to sort that list. The problem is, as far as I know, I cannot use Collections.sort(arr) since I declared it List< Person >, not List< Student >.
Did I misunderstand anything? Is there any way to use Collections.sort() in this situation or I have to write a method to sort it manually?
And he asked us to implement the Comparable interface in the class Student, also asked us to create List< Person > instead of List< Student >
EDIT: THANK YOU VERY MUCH. APPRECIATE ALL OF THE ANSWERS AND COMMENTS. THE ABOVE PROBLEM HAS BEEN SOLVED BY DOWNCAST List< Person > to List < Student >
Personis most likely an abstract class. Then you can declarePersonto implement theComparablebut do the actual code to implementComparablein th the subclasses ofPersononlyList<Person>had aTeacherin it, how would you sort that with respect to theStudents in the list?