How the compareTo method works here to sort objects one by one

I can’t understand how the two objects are compared in the this.User.compareTo (arg0.User) statement. I want to know the comparison thread of an object, like what "this" means when "arg0" is compared.

public class Other implements Comparable<Other>{  // making objects of this class
    public String User;
    public String Pass;
    public String getUser() {
        return User;
    }
    public void setUser(String user) {  //getter and setter
        User = user;
    }
    public String getPass() {
        return Pass;
    }
    public void setPass(String pass) {
        Pass = pass;
    }

    @Override
    public int compareTo(Other arg0) {                   // overriding to comapre objects
        // TODO Auto-generated method stub

        return this.User.compareTo(arg0.User); //here how objects are compared like what "this " 
                              //refers here when we are passing list in Collections.sort(list); 
    }


}

This is the main class.

import java.util.*; 

public class demo 
{
    public static void main(String[] args)
    {
        Other a=new Other();       //creating objects
        a.User="farma";
        a.Pass="123";
        Other a1=new Other();
        a1.User="arma";
        a1.Pass="123";


        Other a2=new Other();
        a2.User="brma";
        a2.Pass="123";
        List<Other> list=new ArrayList<Other>();

        list.add(a);
        list.add(a1);
        list.add(a2);

        Collections.sort(list);                   //sorting

        for (Other other : list) {                         
            System.out.println(other.User+" "+other.Pass);         //printing values
            System.out.println("");

        }

    }  
}
+4
source share
2 answers
 return this.User.compareTo(arg0.User); 

When you write this line, you compare the User object and return the result.

Comes this, which points to the current instance, when you pass the "Other" to this method, it is called in the current instance, which is compared with the passed objects User.

If you see the signature

public class Other implements Comparable<Other>{  // making objects of this class
    public String User;

String, User.

, .

:

Collections, , , . .

+3

User Other String ( , , ). , Other.compareTo() compareTo() Java String. User (, this), Other Other.

String.compareTo() (. ):

0, , ; 0, , , ; 0, , , .

:

Other o1 = new Other();
o1.setUser("Tim Biegeleisen");
Other o2 = new Other();
o2.setUser("Suresh Atta");
System.out.println(o1.compareTo(o2));

1, "Tim Biegeleisen" "Suresh Atta".

+1

Source: https://habr.com/ru/post/1612884/


All Articles