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 .