I have a problem where I have to sort a set of Employees. The employee object has attributes like id, name, designation. Sorting can be on any of the said attribute. The default sort will be based on the id or name.
Now, I have made Employee implement java.lang.Comparable - in which I have provided the default sort. I have 2 java.lang.Comparators for the other 2 sorts. I am trying to have the strategy pattern and decide the sorting. So, for convenience purpose, I write a Comparator for the default sorting too - inside this Comparator's compareTo - I call the emp1.compare(emp2)...
Is this ok? i.e does it make sense to write the comparison directly in the Comparator and not waste one more call?
I know there are different constructors in TreeSet for this scenario, but then I would need a 'if' in my code - which is what I am trying to avoid through the Strategy Pattern.
Thanks for the links. But I do know both these. My question is, can I call emp.compareTo within inside a Comparable - basically aimed at code reuse. I think I can though the need for it maybe wierd....
I suppose you have multiple collation sequences on employees, where one is the default. There is no reason why you shouldn't have a comparator delegating to compareTo(), though personally I'd rather reduce it to just comparators for clarity's sake - usually hard to tell what the 'default' is.
Andrew is right in both his comments, this doesn't really belong here.
author and jackaroo
Its like, in the screen where I list employees (with paging), I provide the sorting option on various columns...
in screens where an employee has to be selected in a dropdown box - the list of employees have to be shown sorted by 'default' name - in this case, the object being Comparable helps...
and in the other screen, I would use Comparator for sorting - in this case, delegating is code reuse - saves me a few keystrokes!