Hi Team,

I am working on Collections and in order to Sort ArrayList of Objects of a Class based on their instance variable, it is mentioned in book that I need to OverRide CompareTo Method.

compareTo Method works fine but Iam not getting the clear idea of its sorting logic. Below is an Example.

public class smalldeer extends deer implements Comparable<smalldeer> {

  private String name;

    public smalldeer(String name) {
        // TODO Auto-generated constructor stub

        this.name=name;

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<smalldeer> s = new ArrayList<smalldeer>();


        smalldeer obj = new smalldeer("Apple");
        smalldeer obj2 = new smalldeer("Orange");
        smalldeer obj3 = new smalldeer("Mango");

        s.add(obj);
        s.add(obj2);
        s.add(obj3);

      Collections.sort(s);

    }

    public String toString(){

        return this.name;

    }

    @Override
    public int compareTo(smalldeer o) {
        // TODO Auto-generated method stub
        String s="";

        System.out.println(name +" "+o.name);

        return name.compareTo(o.name);


    }



}

** OUTPUT is below **

Orange Apple
Mango Orange
Mango Orange
Mango Apple

My doubt is in the below statement

System.out.println(name +" "+o.name);

How does "name" and ""o.name" points to different objects Instance variable ? We are having only one object as a parameter in the compare to method. so both name and o.name should point to the same instance right? so the output should be something like

apple apple
mango mango
orange orange

Please clarify .

suppose the Collections.sort() function is comparing obj(i.e.Apple) and obj2(i.e. Orange)..in that case, name => Apple and o.name => Orange when you're using System.out.println(name +" "+o.name);

that's why you are not getting the same output because, you're printing "name" of different objects.

well ... first of all, you shouldn't use
o.name
you should use mutators (get/set methods) to get that.
name -> like this, is the name of the current instance. it's the same as if you had said: this.name
o.name (what would better be o.getName()) takes the name of the o instance, not of the current one.

also: this is pretty important when you start working on larger projects with different people: follow naming conventions
smalldeer => SmallDeer
deer => Deer
otherwise other people might mistake your classnames for variables.

This question has already been answered. Start a new discussion instead.