Pits related to Java variable-length parameters

Can the following program be compiled normally? Why?

class Demo {
    void func(String arg) {}
    void func(String... args) {}
    void func(String[] vars) {}
}

The above class cannot be compiled, and it will prompt a method duplicate conflict.

Enter image description

Because the variable-length parameter of a java method is just a syntactic sugar, it essentially wraps the variable-length actual parameter args into an array, so String[] args and String... vars will be regarded as methods with the same signature , so it cannot exist at the source level at the same time, so it cannot be compiled.

What is the result of executing the following program segment?

    static void func(Object... varargs) {
        System.out.println(varargs.length);
    }

    public static void main(String[] args) {

        // F1
        func(1024, new String[]{"1", "2", "3"});

        // F2
        func(new String[]{"1", "2", "3"});

        // F3
        func(1024, new Integer[]{1, 2, 3});

        // F4
        func(1, 2, 3);

        // F5
        func(new Integer[]{1, 2, 3});

        // F6
        func(new int[]{1, 2, 3});

        // F7
        func(1024, new int[]{1, 2, 3});

        // F8
        func(null, new int[]{1, 2, 3});

        // F9
        func(new Object[]{new String[]{"1","2","3"}});

        // F10
        func((Object) (new String[]{"1", "2", "3"}));

    }

Enter image description

Since F1 explicitly passes in two actual parameters at compile time, both of which are of type Object, so it can be recognized normally with a length of 2.

Since F2 only passes a String array at compile time, and String is an object type, it is split into array length parameters when passing, so the length is 3.

The principle of F3 at compile time is exactly the same as that of F1.

F4 is the most common normal call, there is no explanation.

The principle of F5 at compile time is exactly the same as that of F2.

When F6 compiles, int[] cannot be directly converted to Object[], because the basic type and Object cannot be matched, so int[] is treated as a simple array object and wrapped into something like Object[]{int[]} form, so the length is 1. And Integer[] itself is Object[], so there is the phenomenon of F2 and F5.

F7 and F8 are the same as F1 and F3 when compiling.

F9 is essentially an element of the Object[] array at compile time, but this element is also a String[] array, so it is printed as 1.

Although F10 is a String[] array at compile time, it is forced to be an Object type when passed to a variable-length parameter, so the entire String[] array is treated as a whole, so the print length is 1.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325065710&siteId=291194637