Search code examples
javacollectionsconstructorcomparatorcompareto

Why do we use `this` in CompareTo in Comparable implementations?


I am somewhat new to java and very new to the Collection framework. I know that this refers to the current object

public class Student implements Comparable <Student> {

    String name;
    int grade;

    public Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }
    public int compareTo(Student s) {
         return this.name.compareTo(s.name);
    }
    public String toString() {
        return this.name + ", " + this.grade;
    }
}

Here this.name is null and s.name does have a value, so what are we trying to do by comparing this.name.compareTo(s.name);

Also what really happens when we do Collections.sort(studentList); ?

The code snippet is just for demo purposes


Solution

  • You are asking two different questions, so I will answer them seperately

    First one which is what are we trying to by comparing this.name.compareTo(s.name);

    When the compareTo method is called on an object of class Student, the this becomes the calling object. Since the calling object (hopefully) has been initialized properly this.name will be the name of the calling object.

    s.name is the name of the Student object passed in to the compareTo method which is again (hopefully) initialized properly and has a name.

    What is boils down to is a String variable calling compareTo passing in a String variable to compare with

    Second is what really happens when we do Collections.sort(studentList);

    Here is the JavaDocs on the Collections.Sort method but you are likely asking about what it does relative to your implementation of Comparable. In short it uses your compareTo method when doing the comparisons for the sort