Search code examples
javaobjectcomparablecompareto

Understanding syntax for compareTo() method in Java


I have created a Student class, which contains roll number, name and age as its data variables. I created an ArrayList for storing multiple objects of class Student.

Now, I have used the Comparable interface and its compareTo method to sort the Student list data according to age.

Below is the compareTo method I have created for sorting age wise:

    public int compareTo(Student sNew)
    {
        return this.age-sNew.age;
    }

Here, I can not understand, What is -? and How it's working?

Because, I have also done it as below :

public int compareTo(Student sNew)
    {
        int returnValue=0;
        if(this.age>sNew.age)
        {
            returnValue=1;
        }else if(this.age<sNew.age){
            returnValue=-1;
        }else if(this.age==sNew.age)
        {
            returnValue=0;
        }
        return returnValue;
    }

So, I have two doubts : How '-' is working in compareTo() method and where it returns the value (0,1,-1).

Please guide.


Solution

  • The idea behind it is that compareTo doesn't return 0,1,-1, but returns 0 (equals), positive number (bigger than) or negative (smaller).

    For that reason, simply subtracting the ages will give you the correct answer