Search code examples
javaarraylistcompareto

How compareTo() method work ArrayList Sorting


I'm new to Java and try to learn Java collections and try to sort arraylist with comparable interface. I follow some tutorials and I'm unable to understand what is happen within the compareto() method here. this is my code.

Student.java

package arraylistexample;

public class Student implements Comparable<Student>{
    private String studentName;
    private int age;
    private int rollno;

    public Student(String studentName, int age, int rollno){
        this.studentName=studentName;
        this.age=age;
        this.rollno=rollno;
    }

    public String getStudent(){
        return studentName;

    }

    public int getAge(){
        return age;
    }

    public int getRollno(){
        return rollno;
    }

     public void setStudent(String Student){
        studentName=Student;
    }

    public void setAge(int age){
        this.age=age;
    }  

    public void setRollno(int rollno){
        this.rollno=rollno;
     }


    public int compareTo(Student compares) {
        int compareage=((Student)compares).getAge();
        /* For Ascending order*/
        return this.age-compareage;

    }


    public String toString() {
        return "[ rollno=" + rollno + ", name=" + studentName + ", age=" + age + "]";
    }
}

ArrayListSorting.java

package arraylistexample;

import java.util.*;


public class ArrayListSorting {
    public static void main(String[] args){
        ArrayList<Student> obj=new ArrayList<Student>();
        obj.add(new Student("Peter", 27,1));
        obj.add(new Student("John",26,7));
        obj.add(new Student("Jack",21,5));

        Collections.sort(obj);

        for(Student str:obj){
            System.out.println(str);
        }
    }

}

The problem is I can't understand how caompareto() method works in here. I googled and read many tutorials. But didn't get clear idea. Can anyone help me.


Solution

  • Writing a compareTo method for your class lets you specify what criteria your program will use to decide which of two objects of that class should come first in order.

    If you don't write a compareTo method for your class, then your program has no way of knowing which order to put two objects in - and therefore it has no way of sorting a whole lot of objects.

    But if you write a compareTo method in your class, AND indicate that your class implements the Comparable interface, then your program will be able to sort any number of objects of that class.

    What that means is that you have to decide what order you want your Student objects to appear in. Maybe you want them sorted by roll number. So you write your compareTo accordingly, like this.

    public int compareTo(Student other) {
        return rollno - other.rollno;
    }
    

    This particular method will return

    • a positive number if the current student has a higher roll number than the student called other,
    • a negative number if the current student has a lower roll number than the student called other.
    • zero if you try to compare a student to itself.

    So it meets all the criteria that a compareTo method has to meet; and it can be used to sort a bunch of students. The actual algorithm that's used for the sort is buried in the Collections.sort method. You don't need to know what it is - you only need to know that it uses your compareTo method in the course of doing the sort.