我正在研究现有代码。在代码中,正在创建对象列表,然后在此列表中使用Collections.sort和Collections.reverse。
以下是他们想要比较的课程的一个小例子:
public class Student implements Comparable<Student> {
public int compareTo(Student s) {
//code comparing the instance's score to parameter score
}
}
列表的类型为Student,输出是基于得分的降序对象。让实例知道自己的另一个实例是好还是坏?
我使用Comparable的问题是,有更好的方法来实现他们想要实现的目标吗?
编辑:仍然习惯向其他人解释我的问题。我还是学生,所以谢谢你的提示。
答案 0 :(得分:0)
另一种可能的方法是实现Comparator并将其作为Collection.sort方法的参数提供。与此类似:
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
};
Collections.sort(yourList, comparator);
你的列表是List<Integer> yourList = new ArrayList<>();
答案 1 :(得分:0)
您描述现有代码的方式反映了这种情况的最佳实践。这就是compareTo应该如何工作的方式。您可以提供Comparator的外部实现,但这里没有充分的理由这样做。