我在做作业时遇到了一个小问题。
我有一个 Person 类
public class Person {
protected String code;
protected String name;
}
还有一个名为 Student 的子类
public class Student extends Person implements Comparable<Student>{
private double grade;
@Override
public int compareTo(Student that){
return Double.compare(grade, that.grade);
}
}
老师希望我们创建一个Professor类来使用ArrayList来管理Student
public class Professor {
private List<Person> arr;
public Professor() {
arr = new ArrayList();
}
}
将大约十名学生添加到 ArrayList 后,我们被要求对该列表进行排序。问题是,据我所知,我无法使用 Collections.sort(arr) 因为我声明它为 List< Person >,而不是 List< Student >。
我是不是误会了什么?在这种情况下有什么方法可以使用 Collections.sort() 或者我必须编写一个方法来手动排序?
并且他要求我们在Student类中实现Comparable接口(interface),还要求我们创建List
编辑:非常感谢。感谢所有的答案和评论。上述问题已通过 DOWNCAST List< Person > 到 List < Student >
解决最佳答案
The teacher wanted us to create a Professor class to manage Student using ArrayList
所以替换
private List<Person> arr;
作者:
private List<Student> students;
这样,你就可以调用 Collections.sort(students)
如student
指的是 List
的Comparable
元素( Student
实现 Comparable
接口(interface))。
评论后编辑:
这个要求不太符合逻辑:您必须对不可排序的内容( List<Person>
)进行排序(因为只有 Student
实现 Comparable
)。
在这些情况下,您有三种方法:
最简单、最干净的方法(如果你可以使用的话)。
制作Person
一个abstract
实现Comparable
的类但保持抽象。
这样您就不需要使用任何强制转换。你可以直接调用Collections.sort()
与List<Person>
强制
List<Person>
的沮丧至List<Student>
并调用 然后Collections.sort()
.自行进行排序,但如果您想使用
compareTo()
,您仍然应该进行一些转换。Student
的方法类为Person
不是Comparable
实例。
关于java - 如果我在子类中实现 Comparable 接口(interface),如何使用 Collections.sort() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44871490/