Lanka
Lanka

Reputation: 3

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.

Upvotes: 0

Views: 12707

Answers (4)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79877

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.

Upvotes: 2

bhavya.work
bhavya.work

Reputation: 421

For sorting collections a compareTo function is used to see if object1 is bigger or smaller than object2 by doing

object1.compareTo(object2)

According to documentation of Intger Object's compareTo

the value 0 if this Integer is equal to the argument Integer; a value less than 0 if this Integer is numerically less than the argument Integer; and a value greater than 0 if this Integer is numerically greater than the argument Integer (signed comparison).

You can find a similar documentation for String Object. This same practice is used for all objects generally.

So, the idea is that the compareTo method in your class should basically return

  1. <0 if object1 < object2
  2. =0 if object1 = object2
  3. >0 if object1 > object2

Using this the Collections API can sort objects.


So, in your case you can see

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

}

is used where it is allowing comparison of students based on their age.

Upvotes: 0

mhasan
mhasan

Reputation: 3709

How compareTo works

If the two elements (a,b) being compared are already in the right order, a.compareTo(b) will return a value that is <= 0, so nothing has to happen.

If they aren't in the right order, the return value is > 0, indicating that they must be interchanged.

So in your case student object passed in your compareTo method whose age is greater than your reference object (this) student age they get interchanged to default sorting which is ascending.

Upvotes: 3

MordechayS
MordechayS

Reputation: 1546

From Oracle docs of the compareTo method:

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

When you implement the method for your own composite-object, you are creating a way to compare those objects.

For example:

A Student named "Peter" and a 'Student named "Greg" - who is bigger/smaller?

That's up to you to decide... You can either choose alphabetical order of name, or ages, or any other component/member/logic to decide.

Edit: As mentioned by Eran in the comments, the way Collections.sort works is using the compareTo method. From the docs:

orts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

Upvotes: 2

Related Questions