I am working on existing code. In the code a list of objects is being created then Collections.sort and Collections.reverse are used on this list.
Here is a small example of the class they wanted to be comparable:
public class Student implements Comparable<Student> {
public int compareTo(Student s) {
//code comparing the instance's score to parameter score
}
}
The list is of type Student and the output is the objects in descending order based on score. Is it good or bad practice to have an instance know about another instance of itself?
My question with using the Comparable, is there a better way to accomplish what they were trying to achieve?
EDIT: Still getting used to explaining my questions to other people. I am still a student, so thank you for that tip.
The way that you describe the existing code reflects best practice for this situation. This is how compareTo is supposed to work. You could provide an external implementation of a Comparator, but there is no good reason to do so here.