D pisces wrote:it states like for comparable interface "you must modify the class whose instances you want to sort" and for comparator "you build a class separate from the class whose instances you want to sort" . Please explain me about these differences sir.
Suppose you have a class called Number. It looks like this:
To add natural ordering to this class, you need to be able to modify its source code thus
you must modify the class whose instances you want to sort.
So you go like this:
What if you can't modify the source code of
Number but you need to provide some ordering? Or you want to provide different ordering that natural ordering of
Number?
You write a comparator. And this comparator is a separate class.
Like this:
Thus
you build a class separate from the class whose instances you want to sort.