For natural ordering , I was using comparable and I found as soon as I use the method
public int compareTo(T o1) {
System.err.println("this "+this.empID+" that "+((Employee<T>)o1).empID);
return this.empID - ((Employee<T>)o1).empID;
}
It works fine, but the this.empID is coming with some logic and that I am not able to figure out. So what is the logic behind this.empID values and what is iteration , is it like on calling sort method , internally the algo is taking care that part (sorting algorithm)
For Example :
on trying to print this.empID and that the output is
this 1 that 5
this 6 that 1
this 6 that 5
this 3 that 5
this 3 that 1
this 7 that 5
this 7 that 6
this 4 that 5
this 4 that 3
this 8 that 5
this 8 that 7
this 2 that 5
this 2 that 3
this 2 that 1
From where the value of this is coming , or what is the iteration logic, is it because of Sorting algorithm.
If your question is about what code is calling your compareTo
method, you're right that it will generally be called as part of a sorting algorithm. For example, if you insert an Employee a
into a TreeSet which contains Employee b
(say), you may see calls like a.compareTo(b)
or b.compareTo(a)
, depending on the exact sorting algorithm. In the first case, this
is a
, and in the second case this
is b
and that
is a
.
To see which code is calling compareTo()
, you can set a breakpoint in that method and use a debugger. Alternatively, a quick and crude technique to see the stack traces of the calls is to add the following to compareTo()
Exception e = new Exception(); // This prepares a call stack
e.printStackTrace(); // This prints it
Obviously, this kind of debug output is very costly in performance terms, as well as verbose, so it should not be left in production code.