Suhaas Parekh wrote:Why does the compare method in Comparator take 2 arguments while the compareTo method in Comparable takes one parameter as this argument and another argument is passed to the method?
Is the compare method in Comparator a static method? Is that the reason for accepting 2 arguments?
Campbell Ritchie wrote:The compareTo() method does take two references. One is the reference it is called on, and the other that passed as an argument.
Suhaas Parekh wrote:Does the compare method in the Integer class override the one declared in the Comparator?
From the doc, I see that Integer class implements the Comparable interface not the Comparator.
Suhaas Parekh wrote:Well if compare and compareTo can be used interchangeably, why is the example below not working?
Rob Spoor wrote:Note that I never said that compare and compareTo are interchangeable. compare belongs to Comparator and takes two arguments. compareTo belongs to Comparable and takes an instance to compare and another argument. What I said is that you can easily create a Comparable based on a Comparable.
Rob corrected wrote:What I said is that you can easily create a Comparator based on a Comparable.
Jesse Silverman wrote:To continue to remember which is which even when jumping around from language to language and not doing any comparisons for a long time, I always remembered Comparator as being short for "Custom Comparator".
When there are multiple different ways to possibly compare two objects of some class T, and one is considered natural or normal enough to implement Comparable<T>, but you may have good reason to sometimes sort them in other ways, you can use "Custom Comparators" to obtain those variant orderings where you need them.