Jhon Clay wrote:In the below code when i sort the array , they are passing to entries of map and comparator, then why do we have compare and compareTo both , what is called for comparing ?
As others have said: either.
There are
two ways to compare objects of similar types (ie, classes):
1. Make the class
Comparable. This is done by having it implement the
Comparable interface, which defines the
compareTo() method.
2. Supply a
Comparator, which is an implementation of the
Comparator interface, which defines the
compare() method.
In the first case, the method is part of the object, so it only needs one argument (the object that
this is being compared to). In the second, the
Comparator is a completely separate object, so you have to supply
both of the objects being compared.
Also: you can only implement
Comparable once, so a class can only have
one compareTo() order - often called its "natural" order. On the other hand, you can create as many
Comparator objects as you like to implement other ones.
I'm a bit worried about your code though. These days, both interfaces use generics, whereas your code doesn't have any at all, and uses casting to ensure success.
If you wrote it yourself, then it's bad practice. If it was written by someone else, then it may be very old and in need of refactoring.
Unfortunately, only you can tell us which.
Winston