Why does Java allow the Comparator comparison method (String, String) to accept object type arguments?

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 two String variables as an argument. However, even when I enter 2 arguments of type Object, it still works. Why is this?

PS: if I define some ordinary method as follows, then the compiler will complain about the error, because the 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!
}
+4
source share
1 answer

You can use Objectas arguments here because you used a raw type Comparator, which you usually should not do.

This is where you did it:

Comparator c = SORT_BY_LENGTH;

, Comparator? . , SORT_BY_LENGTH, . , Comparator , compare Object String s. , - compare.

, , . new Object()!

raw. . - :

Comparator<String> c = SORT_BY_LENGTH;

SORT_BY_LENGTH .

, compare , String s. o1 o2 String.

+9

Source: https://habr.com/ru/post/1695850/


All Articles