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



    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");




    public String toString(){

        return this.name;


    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 .

3 Years
Discussion Span
Last Post by murali2489

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
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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.