I have a list of objects I need to sort on a field, say Score. Without giving much thought I wrote a new class that implements Comparator, that does the task and it works.
Now looking back at this, I am wondering if I should have instead have the my class implement Comparable instead of creating a new class that implements Comparator. The score is the only field that the objects will be ordered on.
What I have done acceptable as a practice?
Is the right approach "First have the class implement Comparable (for the natural ordering) and if an alternative field comparison is required, then create a new class that implements Comparator" ?
If (2) above is true, then does it mean that one should implement Comparator only after they have the class implement Comparable? (Assuming I own the original class).
I would say:
My need was sort based on date.
So, I used Comparable and it worked easily for me.
One restriction with Comparable is that they cannot used for Collections other than List.
There had been a similar question here: When should a class be Comparable and/or Comparator?
I would say the following: Implement Comparable for something like a natural ordering, e.g. based on an internal ID
Implement a Comparator if you have a more complex comparing algorithm, e.g. multiple fields and so on.
If you need natural order sorting -- User Comparable IF you need Custom Order Sorting - Use Comparator
Example:
Natural order Sorting would be based on id because it would be unique and custom order sortin g would be name and department.
Refrences:
When should a class be Comparable and/or Comparator? http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html
The following points help you in deciding in which situations one should use Comparable and in which Comparator:
1) Code Availabilty
2) Single Versus Multiple Sorting Criteria
3) Arays.sort() and Collection.sort()
4) As keys in SortedMap and SortedSet
5) More Number of classes Versus flexibility
6) Interclass comparisions
7) Natural Order
For more detailed article you can refer When to use comparable and when to use comparator