user123 user123 - 2 months ago 4x
Java Question

what is the current object referred to while calling collections.sort() method inside a class which implements Comparable interface?

public class TestSort3{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));

for(Student st:al){
System.out.println(st.rollno+" "" "+st.age);

The definition of
is stated as :

class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){

public int compareTo(Student st){
return 0;
else if(age>st.age)
return 1;
return -1;

I am unable to get the logic by which age is compared inside
method. When
method is called ,
will be called and we have passed the instance of
, so it takes an instance of
class is passed, now which is the other
instance with which it is compared?

I have already gone through other stackoverflow links related to this method, but I am unable to get my doubt clarified, please clarify this.

  • Every student object will be compared with other student object in your list.
  • So when one student object age will be compared with other student object age that is passed as a parameter in compareTo method.

Let us say we have three students as below.

Student vijay = new Student(101, "vijay", 23);
Student ajay= new Student(106, "Ajay", 27); 
Student jai= new Student(105, "jai", 21);
  • you have a student vijay i.e. new Student(101,"Vijay",23)
  • compareTo() method is being called in vijay, it will be compared with ajay that is defined by new Student(106,"Ajay", 26 ).
  • compareTo() method is impelemented in such way that age will be compared and vijay will be logically less than Ajay.
  • returning 0 means objects are logically equal
  • returning negative integer means this object is less than object passed to compareTo method.
  • returning positive integer means this object is logically greater than object passed to compareTo() method.

Overall, - vijay will be compared with ajay and due to our implementation, vijay is logically less than ajay. - ajay will be compared with jaiand ajay will be logically greater than jai

This kind of process will happen for elements with all combinations and final result will be in increasing order of age, i.e. jai < vijay < ajay

There are different sorting algorithms implemented in java which will be selected based on certain scenario which are irrelevant to our question.