简体   繁体   English

为什么我要在java中使用null(String [])null?

[英]Why should I use (String[])null over null in java?

In some snippets, I noticed that the array is initialized by casting the null value to String array like: 在一些片段中,我注意到通过将null值转换为String数组来初始化数组,如:

String[] array = (String[])null;

Generally, null is used to initialize variables eg an array of strings like: 通常, null用于初始化变量,例如字符串数组,如:

String[] array = null;

When or why should I cast null values to string array or any other data type like this? 何时或为什么要将空值转换为字符串数组或任何其他类似的数据类型?

There is no need to use 没有必要使用

String[] array = (String[]) null;

You might have to use (String[]) null if you pass a null value to an overloaded method (ie one of multiple methods having the same name) and you want the method that accepts a String[] argument to be chosen by the compiler. 如果将null值传递给重载方法(即具有相同名称的多个方法之一)并且您希望编译器选择接受String[]参数的方法,则可能必须使用(String[]) null

For example, if you have the following methods : 例如,如果您有以下方法:

public void doSomething (Integer i) {}
public void doSomething (String s) {}
public void doSomething (String[] arr) {}

Calling doSomething (null) will not pass compilation, since the compiler won't know which method to choose. 调用doSomething (null)不会传递编译,因为编译器不知道选择哪种方法。

Calling doSomething ((String[]) null) will execute the 3rd method. 调用doSomething ((String[]) null)将执行第3个方法。

Of course, you can assign the null to a String[] variable, and avoid the casting : 当然,您可以将null赋给String[]变量,并避免转换:

String[] arr = null;
doSomething (arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM