mohitkumar gupta wrote:The other handy thing about
the Comparator interface is that you can use it to sort instances of any class—even
classes you can't modify—unlike the Comparable interface, which forces you to
change the class whose instances you want to sort.
i just cannot understand that while using Comparable interface how are we changing the class
Say you have 2
String objects that you want to compare. String implements Comparable which means it has a compareTo method that compares Strings alphabetically so "Apple" comes before "Bed" which comes before "Cork".
Say, for whatever reason, in your program that you want Strings to be ordered by the length of the String i.e. "Bed" (3 characters) comes before "Cork" (4 characters) which comes before "Apple" (5 characters).
You do not have access to the String class - you can't modify the compareTo method of String.java.
But you can write a new class
Hoever, if you have objects of your own class you want to compare - you can do it by modifying your own class:
So in the first example you didn't modify the class you wanted to compare (String class) but in the second example, you could modify it (MyClass class).