Employee ID sort can be done using Comparable also as well as Comparator also but Why we go for Comparable when it comes to ID Sorting and why we go for Comparator when it comes to Name's sorting etc...?? Why can't we use Only Comparator for all the work???
2 Answers
If you want, you can use Comparator
only. It allows you to freely define arbitrary ways to order object instances (independent of the object's own implementation).
The idea behind Comparable
is that there may be a "natural" way to compare instances of some classes. For example, String
can be compared to other String
s (to get lexicographical ordering). The class can then "advertise" this natural ordering and make it conveniently accessible.
I don't know if it makes sense for your Employee
class to declare ID ordering "natural". Either way, you can only "promote" one order to be the natural one (and it cannot be changed without changing the implementation and contract of the class, so choose wisely).

- 257,207
- 101
- 511
- 656
Comparable
is usually used to define a natural ordering (or you can call it a default ordering) on the instances of the class in which it is implemented.
In your Employee
example (which is not detailed enough), I can assume that the employee ID is a unique identifier that identifies each employee, so it makes a good candidate for use in the definition of the natural ordering.
The Comparator
interface allows us to implement additional orderings on instances of the Employee
class, such as ordering by name, age, etc...
You could use just Comparator
, but whenever a class has a natural ordering, it makes sense to implement Comparable
, which allows you to use some classes and methods that require ordering (TreeSet
, Collections.sort()
, etc...) without having to pass a Comparator
instance.

- 387,369
- 54
- 702
- 768
-
1"which allows you to use some classes and methods that require ordering (TreeSet, Collections.sort(), etc...) without having to pass a Comparator instance" This answer satisfies the question. Thank you:) – Naveen Shriyan Feb 22 '16 at 10:59