Varargs在Java中使用null参数 [英] Varargs with null parameters in Java
问题描述
以下代码只使用空引用作为varargs参数。
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);
}
}
第一次调用方法 temp(null,null);
显示 [null,null]
表示 str [0] = null
和 str [1] = null
。
The first call to the method temp(null, null);
displays [null, null]
means that str[0]=null
and str[1]=null
.
但稍后调用 temp(null);
导致 NullPointerException
被抛出,看起来 str
本身是 null
。
but the later call to temp(null);
causes the NullPointerException
to be thrown which appears that the str
itself is null
.
如果它的类型转换为 String
类似这样的 temp((String)null);
,它可以工作并显示 [null]
。
If it's type cast to String
something like this temp((String)null);
, it works and displays [null]
.
为什么在最后一次调用中,需要显式类型转换? 在我看来,它被认为是一个带有 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?
推荐答案
在我看来,它被认为是一个带有$ b $的字符串数组b与第一次调用不同的参考
It seems to me that it's considered to be a string array with a null reference which is different from the first call
完全正确。这就是发生的事情。
Exactly. This is what happening.
实际上,它只是优先级
之间: - exact-匹配
, var-args
,拳击
和类型转换
。
Actually, it's just about precedence
between: - exact-match
, var-args
, boxing
and type-casting
.
在检查要调用的方法或参数的传递方式时,编译器遵循以下优先顺序: -
Compiler follow the following precedence when checking for methods to be called, or how the argument will be passed: -
完全匹配>类型投射>拳击>变种参数
Exact-Match > Type-Cast > Boxing > Var-args
所以,你可以看到, var-args
具有最低优先级, exact-match
具有最高优先权。这意味着,如果参数
足够
,完全匹配
那么它将被视为这样。
So, you can see that, var-args
has the lowest precedence, and exact-match
has the highest precedence. That means, if an argument
is good-enough
for an exact-match
then it will be considered as such.
现在,当你传递 null
作为参数时,那么 null
可以直接传递给你的 var-args
参数作为的引用值
。这个参数是完全匹配
。
所以,你需要 typecast
它显式地 String
告诉它实际上是你的 var-args
参数的第一个元素
Now, when you pass null
as an argument, then null
can directly be passed to your var-args
parameter as the value of reference
. It is an exact match
for the parameter.
So, you need to typecast
it explicitly to String
to tell that its actually the first element of your var-args
parameter
然而,在 null,null
的情况下,它将被视为两个
元素您的 var-args
。因为它不能是的参考值
。
Whereas, in case of null, null
, it will be taken as two
elements of your var-args
. As it cannot be a value of reference
.
这篇关于Varargs在Java中使用null参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!