8

The following code simply uses a null reference as a varargs parameter.

package currenttime;

import java.util.Arrays;

public class Main
{
    private static void temp(String...str)
    {
        System.out.println(Arrays.asList(str));
    }

    public static void main(String[] args)
    {
        temp(null,null);
        temp(null);
    }
}

The first call to the method temp(null, null); displays [null, null] means that str[0]=null and str[1]=null.

but the later call to temp(null); causes the NullPointerException to be thrown which appears that the str itself is null.

If it's type cast to String something like this temp((String)null);, it works and displays [null].

Why in the last call, an explicit type cast is required? It seems to me that it's considered to be a string array with a null reference which is different from the first call. What is the correct answer?

4

1 回答 1

12

在我看来,它被认为是一个带有空引用的字符串数组,这与第一次调用不同

确切地。这就是正在发生的事情。

实际上,它只是precedence介于: - exact-matchvar-argsboxing之间type-casting

编译器在检查要调用的方法或如何传递参数时遵循以下优先级:-

Exact-Match > Type-Cast > Boxing > Var-args

所以,你可以看到,var-args它的优先级最低,而exact-match优先级最高。这意味着,如果 an代表 an那么它将argument被视为这样。good-enoughexact-match

现在,当您null作为参数传递时, thennull可以直接var-args作为value of reference. 它是一个exact match参数。
因此,您需要typecast明确String告诉它它实际上是var-args参数的第一个元素

而在 的情况下null, null,它将被视为two您的元素var-args。因为它不能是value of reference.

于 2012-10-13T04:48:43.600 回答