The answer code which you have mentioned is correct!
Let me explain you the code in a detailed manner. First,let's check the definition.
public class DoubleKey<K extends Comparable<K>, J extends Comparable<J>>
implements Comparable<DoubleKey<K, J>>
It is correct as Comparable is itself a generic interface and Comparable
is being implemented by DoubleKey Class
.Pay special attention to the way that the type parameters K and J are decalred by DoubleKey Class and then passed to Comparable Interface,it is OK to declare in this way! I hope it clears your first doubt!
Next,your second doubt is recursive call in compareTO() method
!Though it seems apparently at first sight,but it ain't exactly so. On careful judgement you will find that it won't do recursion as the code will not be called because of lack of Object.
To clarify more,
public int compareTo(DoubleKey<K, J> that) {
int cmp = this.getFirstKey().compareTo(that.getFirstKey());
if (cmp == 0)
cmp = this.getSecondKey().compareTo(that.getSecondKey());
return cmp;
}
It is firstly calling this(the current calling object)
,then calling getFirstKey()
on it and then calling standard Comparable interface's compareTo()
method. Next,the parameter being passed to compareTo()
method in the inner-definition of outer compareTo()
method is of type that.getgetSecondarykey()
.It doesn't match the parameter of type of outer compareTo()
method as outer compareTo() method has argument of type DoubleKey whereas inner compareTo() method has arguments of type that.getSecondaryKey()
---referentially J.
So,now,clearly,parameters passed to outer and inner compareTo()
methods differ.Inner compareTo() is the standard compareTo()
as defined in Comparable Interface and that's why the author has implemented Comparable Interface!
For more clarity,I am simplifying parameters for you of both methods :-
Outer compareTo()(DoubleKey<K,J> that) //parameter is of type DoubleKey<K,J>
Inner first compareTo()(K key1) //parameter of type K for first Inner method
Innner second compareTo()(J key2) //parameter of type J for second Inner method
I hope it answers all your doubts.Please comment if you couldn't understand! Also,SORRY for mis-informing you that time.Answer accepted is damn correct and justified in my answer!!!