So here is my code:
public class Demo {
public static final Comparator<String> SORT_BY_LENGTH = new SortByLength();
private static class SortByLength implements Comparator<String>{
public int compare(String w, String v) {
return w.length()-v.length();
}
}
public static void main(String[] args) {
Object o1 = "abc", o2 = "bc";
Comparator c = SORT_BY_LENGTH;
System.out.println(c.compare(o1, o2));//OK, output 1
}
}
So what confuses me is that the signature of the compare() method takes 2 String variables as argument. However, even when I input 2 arguments of Object type, it still works. Why is that?
PS: if I define some ordinary method as follows, then the compiler will complain there is an error, because Object cannot be converted to String.
public static int foo(String w, String v) {
return w.length()-v.length();
}
public static void main(String[] args) {
Object o1 = "abc", o2 = "bc";
System.out.println(foo(o1, o2));// compiling error!
}