Suppose I have a Student class with attributes name and id. And I want to sort the List
of students in natural order of their respective ids using Collections.sort()
method. I can do it in following two ways:
public class Student implements Comparable<Student> {
private Long id;
private String name;
// getters and setters..
public int compareTo(Student student){
return this.getId().compareTo(student.getId());
}
}
And the other way is:
public class Student implements Comparable<Long> {
private Long id;
private String name;
// getters and setters..
public int compareTo(Long id){
return this.getId().compareTo(id);
}
}
And then use the Collections.sort()
method to sort the list of students. My question or confusion is what difference does it make if we use one over other as they both produce the same result.
If you implement Comparable<Long>
, Collections.sort()
will not be able to use it on a List<Student>
because Collections.sort()
will have no way of figuring out where to get the Long
from to pass to compareTo(Long)
.